Move the cursor position with Javascript?

ⅰ亾dé卋堺 提交于 2019-11-29 04:22:22

The code snippet you have is for text inputs and textareas, not contenteditable elements.

Provided that all your content is in a single text node and the selection is completely contained within it, the following will work in all major browsers, including IE 6.

Demo: http://jsfiddle.net/9sdrZ/

Code:

function moveCaret(win, charCount) {
    var sel, range;
    if (win.getSelection) {
        // IE9+ and other browsers
        sel = win.getSelection();
        if (sel.rangeCount > 0) {
            var textNode = sel.focusNode;
            var newOffset = sel.focusOffset + charCount;
            sel.collapse(textNode, Math.min(textNode.length, newOffset));
        }
    } else if ( (sel = win.document.selection) ) {
        // IE <= 8
        if (sel.type != "Control") {
            range = sel.createRange();
            range.move("character", charCount);
            range.select();
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!