如何将光标设置在可编辑div中的给定位置

时间:2014-10-14 06:44:45

标签: javascript jquery

我有一个div

<div id="user_status" class="status expanddiv" onkeyup="username_Search('New','user_status');" contenteditable="true" data-text="What's on your mind?...">
 Some Text will goes Here.
</div>

当username_Search函数调用时,它的光标位于0位置。而我需要保持光标在其实际位置。我可以在调用此函数之前获取光标位置。但无法设定。

蚂蚁有解决方案吗?

1 个答案:

答案 0 :(得分:1)

如果您使用的是Chrome或Firefox,则以下代码可以很好地完成任务。此代码未在IE或Safari中测试。

我想要的是setCaretPosition函数

function getCaretPosition(editableDiv) {
            var caretPos = 0, containerEl = null, sel, range;
            if (window.getSelection) {
                sel = window.getSelection();
                if (sel.rangeCount) {
                    range = sel.getRangeAt(0);
                    if (range.commonAncestorContainer.parentNode == editableDiv) {
                        caretPos = range.endOffset;
                    }
                }
            } 
            return caretPos;
        }

function setCaretPosition(ctrl, pos) {
            if (window.getSelection) {
                pos = (ctrl.textContent.length > pos ? pos : ctrl.textContent.length);
                var selection = window.getSelection();
                var range = document.createRange();
                range.selectNodeContents(ctrl.childNodes[0]);
                range.endOffset = pos;
                selection.removeAllRanges();
                selection.addRange(range);
                selection.collapse(ctrl.childNodes[0], pos);
            }
}

function username_Search(st,str)
{
   var ctl = document.getElementById('user_status');
var pos = getCaretPosition(ctl);
    document.getElementById("user_status").textContent 
= "dsdssadsadasdffstjdyjdrtyurtystseryds";
    setCaretPosition(ctl,pos);
}
<div id="user_status" class="status expanddiv" onkeyup="username_Search('New','user_status');" contenteditable="true" data-text="What's on your mind?...">
 Some Text will goes Here.
</div>