Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/jpa/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript js/jquery:contenteditable,插入文本并将光标移动到末尾_Javascript_Jquery_Dom - Fatal编程技术网

Javascript js/jquery:contenteditable,插入文本并将光标移动到末尾

Javascript js/jquery:contenteditable,插入文本并将光标移动到末尾,javascript,jquery,dom,Javascript,Jquery,Dom,我需要将文本插入contenteditable div,然后将光标放在插入文本的末尾 我从这里得到了下面的解决方案 如果将文本添加到am empty div中,这将非常有效。但是如果用户已经输入了文本,这将不起作用。或者,如果该函数用于插入文本,则用户将光标放在新插入的文本中的某个位置,然后再次调用该函数。然后光标留在插入文本的开头 编辑:下面的代码在IE中工作,正确设置光标,但在Chrome中有问题 function insertTextAtCursor(text) { var sel

我需要将文本插入contenteditable div,然后将光标放在插入文本的末尾

我从这里得到了下面的解决方案

如果将文本添加到am empty div中,这将非常有效。但是如果用户已经输入了文本,这将不起作用。或者,如果该函数用于插入文本,则用户将光标放在新插入的文本中的某个位置,然后再次调用该函数。然后光标留在插入文本的开头

编辑:下面的代码在IE中工作,正确设置光标,但在Chrome中有问题

function insertTextAtCursor(text) {
    var sel, range, html;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            range = sel.getRangeAt(0);
            range.deleteContents();
            range.insertNode( document.createTextNode(text) );
        }
    } else if (document.selection && document.selection.createRange) {
        document.selection.createRange().text = text;
    }
}

好吧,当我意识到这是一个Chrome/IE的东西时,我设法在我第一次找到答案的一条评论中找到了答案

function insertTextAtCursor(text) { 
    var sel, range, html; 
    sel = window.getSelection();
    range = sel.getRangeAt(0); 
    range.deleteContents(); 
    var textNode = document.createTextNode(text);
    range.insertNode(textNode);
    range.setStartAfter(textNode);
    sel.removeAllRanges();
    sel.addRange(range);        
}
我这里有一个jsfiddle,通过给出一个空div和非空div场景的示例来启发我。谢谢