【问题标题】:Caret index in nested node javascript嵌套节点javascript中的插入符号索引
【发布时间】:2012-12-18 11:14:25
【问题描述】:

我正在尝试在其中包含嵌套节点的可编辑 div 中查找插入符号的选择索引。

示例(| 是光标):

<div contenteditable="true">1234<span>5678|9</span></div> //Returns 4

我想要div中所有字符的索引,所以上面的例子应该返回8。

这是我目前正在使用的。

var sel = window.getSelection();
    return sel.anchorOffset;

我尝试过使用 commonAncestor 以及其他选择和范围方法,但我不确定如何找到它。

【问题讨论】:

标签: javascript dom range selection


【解决方案1】:

遍历树! Here’s a demo.

function getSelectionOffsetFrom(parent) {
    var sel = window.getSelection();
    var current = sel.anchorNode;
    var offset = sel.anchorOffset;

    while(current && current !== parent) {
        var sibling = current;

        while(sibling = sibling.previousSibling) {
            if(sibling.nodeType === 3) {
                offset += sibling.nodeValue.length;
            } else if(sibling.nodeType === 1) {
                offset += getContentLength(sibling);
            }
        }

        current = current.parentNode;
    }

    if(!current) {
        return null;
    }

    return offset;
}

function getContentLength(element) {
    var stack = [element];
    var total = 0;
    var current;

    while(current = stack.pop()) {
        for(var i = 0; i < current.childNodes.length; i++) {
            if(current.childNodes[i].nodeType === 1) {
                stack.push(current.childNodes[i]);
            } else if(current.childNodes[i].nodeType === 3) {
                total += current.childNodes[i].nodeValue.length;
            }
        }
    }

    return total;
}

【讨论】:

  • 感谢您的示例!唯一的问题是跨度之后是否有文本。将插入符号放入 10。jsfiddle.net/ybn6e/1
  • @GrantKiely:啊。正确的。请稍等!您需要什么样的浏览器兼容性?
  • @GrantKiely:啊,好吧,你可以使用offset += sibling.textContent.length; 代替我刚刚添加的getContentLength(),然后:)
  • 绝对是一种享受!我不敢相信你才 15 岁。是的,我使用了 += textContent.length,它更整洁 :)
  • 这很好,但实际上不需要进行遍历:您可以创建一个从 contenteditable 元素开始到插入符号位置的范围,并使用其toString() 方法。见stackoverflow.com/questions/4811822/…
猜你喜欢
  • 1970-01-01
  • 2010-11-30
  • 2012-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多