将光标设置为contenteditable div的结尾

时间:2012-11-22 13:02:46

标签: javascript jquery html5 contenteditable

我试图将光标设置为next / prev contenteditable标记的末尾,如果当前的标记为空,但是当我设置焦点时,它会将焦点添加到文本的开头而不是结束 在SO上尝试了几乎所有解决方案,但似乎没有一个对我有用。这里是我正在尝试的简单代码

HTML CODE

<div id = 'main'>
<div id = 'n1' contenteditable=true> Content one</div>
<div id = 'n2' contenteditable=true> Content 2</div>
<div id = 'n3' contenteditable=true> Content 3</div>
<div id = 'n4' contenteditable=true> Content 4</div>

JS CODE

$('#main div').keydown(function(){
if(!$(this).text().trim()){
    $(this).prev().focus();
   //setCursorToEnd(this.prev())
    }
});


function setCursorToEnd(ele)
  {
    var range = document.createRange();
    var sel = window.getSelection();
    range.setStart(ele, 1);
    range.collapse(true);
    sel.removeAllRanges();
    sel.addRange(range);
    ele.focus();
  }

3 个答案:

答案 0 :(得分:14)

您正在使用jQuery并从jQuery获取元素。您必须将其转换为本机DOM元素(通过jQuery-get函数)才能使用“setCurserToEnd” - 函数:

你的方法调用:

setCursorToEnd(this.prev());

工作解决方案:

setCursorToEnd($(this).prev().get(0));

请参阅更新的小提琴:http://jsfiddle.net/dvH5r/4/

答案 1 :(得分:2)

你非常接近,唯一的问题是prev()返回一个jQuery对象,而你想将实际的DOM元素传递给setCursorToEnd()

成品:http://jsfiddle.net/B5GuC/

*注意:即使上面的div元素为空,这也有效。 Vanilla js ftw。

$('#main div').keydown(function(){
    if(!$(this).text().trim()){
        $(this).prev().focus();
        setCursorToEnd(getPrevSib(this));
    }
});

function setCursorToEnd(ele){
    var range = document.createRange();
    var sel = window.getSelection();
    range.setStart(ele, 1);
    range.collapse(true);
    sel.removeAllRanges();
    sel.addRange(range);
}

function getPrevSib(n){
    //gets prev sibling excl whitespace || text nodes
    var x=n.previousSibling;
    while (x && x.nodeType!=1){
          x=x.previousSibling;
    }
    return x;
}

答案 2 :(得分:0)

建议您使用plugi jCaret,因为浏览器在执行此操作时有很大不同。例如,您可以使用

在字段中检索当前位置
$("#myTextInput").bind("keydown keypress mousemove", function() {
  alert("Current position: " + $(this).caret().start);
});

然后您可以使用(不测试它)

来设置位置
var endPos = $(this).caret().end;
$("input:text.hola").caret({start:endPos ,end:endPos });