在嵌套的contentEditable之后设置光标位置

时间:2013-01-22 00:38:52

标签: jquery html contenteditable caret

我有这个标记

<div contentEditable="true">
    Some other editable content
    <div class="field" contentEditable="false">
        <span class="label">This is the label</span>
        <span class="value" contentEditable="true">This is where the caret is</span>
    </div>
    <!-- This is where I want the Caret -->
</div>

插入符号目前位于.field范围内。

我需要将其移回 .field中的contentEditable

Example

如何通过javascript(如果需要使用jQuery)来实现?

当插入符号位于.value范围内时,它将尝试在keydown事件上触发它。如图所示。

2 个答案:

答案 0 :(得分:3)

我假设你想进入下一节。为了说清楚,我添加了一个文本“Here!”在演示中向您展示它确实走到了尽头。

在下面的演示中,从.field .value Enter键即可结束。

DEMO: http://jsfiddle.net/GLzKy/1/

以下是来自https://stackoverflow.com/a/4238971/297641的功能,它实际上完成了所有工作。

$('.field .value').keydown(function (e) {
    if (e.which == 13) { //Enter Key
        e.preventDefault();            
        placeCaretAtEnd($(this).closest('.parent')[0]);
    }
});

/**
  This below function is from https://stackoverflow.com/a/4238971/297641
  All credits goes to the original author.
*/
function placeCaretAtEnd(el) {
    el.focus();
    if (typeof window.getSelection != "undefined"
            && typeof document.createRange != "undefined") {
        var range = document.createRange();
        range.selectNodeContents(el);
        range.collapse(false);
        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    } else if (typeof document.body.createTextRange != "undefined") {
        var textRange = document.body.createTextRange();
        textRange.moveToElementText(el);
        textRange.collapse(false);
        textRange.select();
    }
}

在FF,IE8和Chrome中测试

参考: https://stackoverflow.com/a/4238971/297641

答案 1 :(得分:3)

对上一个答案的更新。 http://jsfiddle.net/GLzKy/4/

placeCaretAtEnd($(this).parent().nextAll('.field').children('value'));

<强>更新

在评论中更正了正确答案的答案

  

要在当前字段之后直接移动,您可能需要使用range.setStartAfter和range.setEndAfter:http://jsfiddle.net/GLzKy/5

相关问题