Javascript Contenteditable - 将Cursor/Caret设置为索引

Rya*_*ing 6 javascript jquery contenteditable

我将如何修改它(如何在contenteditable元素(div)中设置插入符号(光标)?)所以它接受一个数字索引和元素并将光标位置设置为该索引?

例如:如果我有段落:

<p contenteditable="true">This is a paragraph.</p>
Run Code Online (Sandbox Code Playgroud)

我打电话给:

setCaret($(this).get(0), 3)
Run Code Online (Sandbox Code Playgroud)

光标将移动到索引3,如下所示:

Thi|s is a paragraph.
Run Code Online (Sandbox Code Playgroud)

我有这个,但没有运气:

function setCaret(contentEditableElement, index)
{
    var range,selection;
    if(document.createRange)//Firefox, Chrome, Opera, Safari, IE 9+
    {
        range = document.createRange();//Create a range (a range is a like the selection but invisible)
        range.setStart(contentEditableElement,index);
        range.collapse(true);
        selection = window.getSelection();//get the selection object (allows you to change selection)
        selection.removeAllRanges();//remove any selections already made
        selection.addRange(range);//make the range you have just created the visible selection
    }
    else if(document.selection)//IE 8 and lower
    { 
        range = document.body.createTextRange();//Create a range (a range is a like the selection but invisible)
        range.moveToElementText(contentEditableElement);//Select the entire contents of the element with the range
        range.collapse(false);//collapse the range to the end point. false means collapse to end rather than the start
        range.select();//Select the range (make it the visible selection
    }
}
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/BanQU/4/

Tim*_*own 11

这是一个改编自HTML中选择后保持范围对象更改的答案 .请记住,这在几个方面并不完美(正如MaxArt的,使用相同的方法):首先,只考虑文本节点,这意味着隐含的断行<br>和块元素不包含在索引中; 其次,考虑所有文本节点,甚至是那些被CSS或内部<script>元素隐藏的元素内部; 第三,页面上折叠的连续空白字符都包含在索引中; 最后,IE <= 8的规则再次不同,因为它使用不同的机制.

var setSelectionByCharacterOffsets = null;

if (window.getSelection && document.createRange) {
    setSelectionByCharacterOffsets = function(containerEl, start, end) {
        var charIndex = 0, range = document.createRange();
        range.setStart(containerEl, 0);
        range.collapse(true);
        var nodeStack = [containerEl], node, foundStart = false, stop = false;

        while (!stop && (node = nodeStack.pop())) {
            if (node.nodeType == 3) {
                var nextCharIndex = charIndex + node.length;
                if (!foundStart && start >= charIndex && start <= nextCharIndex) {
                    range.setStart(node, start - charIndex);
                    foundStart = true;
                }
                if (foundStart && end >= charIndex && end <= nextCharIndex) {
                    range.setEnd(node, end - charIndex);
                    stop = true;
                }
                charIndex = nextCharIndex;
            } else {
                var i = node.childNodes.length;
                while (i--) {
                    nodeStack.push(node.childNodes[i]);
                }
            }
        }

        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    }
} else if (document.selection) {
    setSelectionByCharacterOffsets = function(containerEl, start, end) {
        var textRange = document.body.createTextRange();
        textRange.moveToElementText(containerEl);
        textRange.collapse(true);
        textRange.moveEnd("character", end);
        textRange.moveStart("character", start);
        textRange.select();
    };
}
Run Code Online (Sandbox Code Playgroud)


Max*_*Art 7

range.setStart并且range.setEnd可以用在文本节点上,而不是元素节点上.否则他们会引发DOM异常.所以你要做的就是

range.setStart(contentEditableElement.firstChild, index);
Run Code Online (Sandbox Code Playgroud)

我不知道你为IE8做了什么以及更低.你在哪里使用index

总的来说,如果节点的内容超过单个文本节点,则代码将失败.isContentEditable === true由于用户可以从Word或其他地方粘贴文本,或者创建新行等,因此可能会出现节点.

这是我在框架中所做的改编:

var setSelectionRange = function(element, start, end) {
    var rng = document.createRange(),
        sel = getSelection(),
        n, o = 0,
        tw = document.createTreeWalker(element, NodeFilter.SHOW_TEXT, null, null);
    while (n = tw.nextNode()) {
        o += n.nodeValue.length;
        if (o > start) {
            rng.setStart(n, n.nodeValue.length + start - o);
            start = Infinity;
        }
        if (o >= end) {
            rng.setEnd(n, n.nodeValue.length + end - o);
            break;
        }
    }
    sel.removeAllRanges();
    sel.addRange(rng);
};

var setCaret = function(element, index) {
    setSelectionRange(element, index, index);
};
Run Code Online (Sandbox Code Playgroud)

这里的技巧是使用setSelectionRange函数 - 选择内部文本范围和元素 - start === end.在contentEditable元素中,这将插入符号放在所需的位置.

这应该适用于所有现代浏览器,以及不仅仅具有文本节点作为后代的元素.我会让你添加支票startend在适当的范围内.

对于IE8及更低版本,事情有点困难.事情看起来有点像这样:

var setSelectionRange = function(element, start, end) {
    var rng = document.body.createTextRange();
    rng.moveToElementText(element);
    rng.moveStart("character", start);
    rng.moveEnd("character", end - element.innerText.length - 1);
    rng.select();
};
Run Code Online (Sandbox Code Playgroud)

这里的问题是,innerText不是好了这样的事情,因为一些白色的空间坍塌.如果只有一个文本节点,情况就好了,但是对于像contentEditable元素一样复杂的东西,它们会被搞砸.

IE8不支持textContent,所以你必须使用a计算字符数TreeWalker.但IE8也不支持TreeWalker,所以你必须自己走DOM树...

我仍然需要解决这个问题,但不知怎的,我怀疑我永远不会.即使我做了代码填充工具用于TreeWalker在IE8和更低...