【问题标题】:How to get the index of the node that is currently editing within the contenteditable div如何在 contenteditable div 中获取当前正在编辑的节点的索引
【发布时间】:2015-12-25 16:35:40
【问题描述】:

我有一个 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,我应该得到索引“@987654328 @"

我有一个函数可以返回我正在编辑的实际节点,但我不确定是否会有所帮助。见jsfiddle

【问题讨论】:

  • 您快到了,使用您的 getEditingNode 函数始终返回 parentNode 而不是返回文本节点。然后遍历所有 document.getElementById('editable').childNodes 并与返回的节点进行比较以获得索引
  • @AlexBarroso,如果我们总是返回parentNode,当用户编辑单词“world”(这是一个文本节点)时,那么父节点将是id为“editable”的div,这是不可取的,对吧?
  • 嗯,是的,您需要做的是尝试返回作为可编辑节点子节点的父元素。
  • 如果world这个词被编辑了会发生什么?
  • @adeneo 它应该返回 1 作为索引,因为它是第二个节点

标签: javascript jquery html contenteditable


【解决方案1】:

我会将文本节点包装在跨度中,因此您只有元素节点,并且只需使用 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

【讨论】:

  • 谢谢,虽然我不会实际包装 span 并修改页面上的实际内容,但我可以通过一些内部处理来做到这一点并得到我想要的。
【解决方案2】:

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

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 将根据需要正确给出。

【讨论】:

  • 如果 html 是
    dear world helloflower
    ,当我编辑花,索引还是1,不对
  • @KesongXie 确实。正如 Adeneo 指出的那样,将文本节点包裹在一个跨度中将解决它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-01
  • 2018-02-25
  • 2011-03-08
  • 2020-05-12
  • 1970-01-01
  • 2020-11-07
相关资源
最近更新 更多