如何获取当前在 contenteditable div 中编辑的节点的索引

How to get the index of the node that is currently editing within the contenteditable div

我有一个 contenteditable div,在这个 div 里面,我有 3 个节点

<div id="editable" contenteditable="true"><span>dear</span>world<span>hello</span></div> 

在这种情况下,如果我们使用下面的代码:

console.log(document.getElementById('editable').childNodes)

我们会有类似 [span, text, span] 的内容。如何获取正在编辑的节点的索引。例如,如果用户正在编辑单词dear,我应该得到索引“0”,因为它是第一个节点,如果用户正在编辑单词hello,我应该获取索引“2

我有一个功能可以 return 我正在编辑的实际节点,但我不确定是否有帮助。见 jsfiddle.

这里有一个更简单的方法来获得你想要的东西:

var node = null;
node = window.getSelection().getRangeAt(0).commonAncestorContainer;
node = ((node.nodeType===1)?node:node.parentNode);    

var idx = Array.prototype.indexOf.call(node.parentNode.childNodes,node);

idx会根据您的要求正确给出。

我会将文本节点包裹在 span 中,因此您只有元素节点,只需使用 jQuery 的 index() 来获取索引

$('#editable').on('keydown', function(e){
    var _node = document.getSelection().anchorNode; 
    var node  = _node.nodeType == 3 ? _node.parentNode : _node;
    var index = $(this).children().index(node);

    console.log( index ); // output index

}).contents().each(function(i, node) {
    if (node.nodeType === 3) {
        $(node).wrap('<span />');
    }
});

FIDDLE