嵌套节点javascript中的插入符号索引

嵌套节点javascript中的插入符号索引,javascript,dom,range,selection,Javascript,Dom,Range,Selection,我试图在一个有嵌套节点的可编辑div中找到插入符号的选择索引 示例(|是光标): 我尝试过使用Common祖先和其他选择和范围方法,但我不确定如何找到它。遍历树 函数getSelectionOffsetFrom(父级){ var sel=window.getSelection(); 无功电流=选择固定节点; var偏移=选择锚定偏移; while(当前和当前!==父级){ var同级=当前; while(sibling=sibling.previousSibling){ if(sibling.n

我试图在一个有嵌套节点的可编辑div中找到插入符号的选择索引

示例(|是光标):

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

遍历树

函数getSelectionOffsetFrom(父级){ var sel=window.getSelection(); 无功电流=选择固定节点; var偏移=选择锚定偏移; while(当前和当前!==父级){ var同级=当前; while(sibling=sibling.previousSibling){ if(sibling.nodeType==3){ 偏移量+=同级.nodeValue.length; }else if(sibling.nodeType==1){ 偏移量+=getContentLength(同级); } } current=current.parentNode; } 如果(!当前){ 返回null; } 返回偏移量; } 函数getContentLength(元素){ var堆栈=[element]; var合计=0; 无功电流; while(当前=stack.pop()){ 对于(var i=0;igetRangeAt()返回相同的值请尝试此代码段,可能重复感谢您提供的示例!唯一的问题是跨度后是否有文本。把插入符号放在10@格兰特基利:啊。正确的。等一下你需要什么样的浏览器兼容性?@GrantKiely:啊,好吧,你可以使用
offset+=sibling.textContent.length
而不是我刚才添加的
getContentLength()
东西,然后:)绝对有效!真不敢相信你15岁了。是的,我使用了
+=textContent.length
它更简洁:)这很好,但实际上不需要进行遍历:您可以创建一个范围,从contentedible元素的开始到插入符号位置,并使用其
toString()
方法。看见
<div contenteditable="true">1234<span>5678|9</span></div> //Returns 4
var sel = window.getSelection();
    return sel.anchorOffset;
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;
}