return the range object of the word before or upon carret position in contenteditable div

孤人 提交于 2019-12-25 03:43:15

问题


After research, i came accross few answers by @Tim Down but still did not quench my thirst. What i want is to delete the contents of range containing the word before or upon carret in contenteditable div. Assuming | represent carret position.

Example: @TimDown is a #GoodJavascriptProgrammer| and ....

if i click a delete button, i should delete word #GoodJavascriptProgrammer with # symbol included and set cursor back to its position. see my fiddle delete last string before carret

function delete_last_word_at_carret(el){
if(window.getSelection){//Webkits and Firefox code
    var sel=document.getSelection();
if(sel.getRangeAt && sel.rangeCount){
        range=sel.getRangeAt(0);//assume this is required range
        range.deleteContents();
  //the word #GoodJavascriptProgrammer should be deleted
  //and cursor set back to the right position
   set_cursor();
    }
 }
 else if(document.selection){//IE code
 //help with code here
 }
}
function set_cursor(){
//return cursor
}
//click the delete button
$('.delete_bt').click(function(){
var el=document.getElementById('editable_div');
delete_last_word_at_carret(el);
});

来源:https://stackoverflow.com/questions/53153573/return-the-range-object-of-the-word-before-or-upon-carret-position-in-contentedi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!