范围startContainer不是最深的节点

时间:2012-10-02 13:16:12

标签: javascript range nodes getselection

我想在页面中生成一个节点数组,它将包含Ranges的所有可能的startContainers。

我尝试使用treeWalker,但它给了我一个比实际的startContainer节点更深的节点,例如:

<p>For those keeping count at home, by the way, the <a target="_blank" href="http://msdn.microsoft.com/en-US/windows/apps/br229516.aspx">Windows 8 Developer Preview site</a> still happily talks about "Metro style app development,"; even though <a target="_blank" href="http://www.istartedsomething.com/20120816/microsofts-new-rule-no-metro-named-apps/">rumor has it</a> that Microsoft is now banning all apps with the word "Metro" in their name from the Windows Store.</p>

(取自techcrunch.com)

所以我的树步行者返回以下内容:

['For those keeping count at home, by the way, the ','Windows 8 Developer Preview site',' still happily talks about "Metro style app development,"; even though ','rumor has it',' that Microsoft is now banning all apps with the word "Metro" in their name from the Windows Store.']

(分体式)

但是当我尝试获得以下内容时: window.getSelection()。getRangeAt(0).startContainer.textContent 我明白了:

['For those keeping count at home, by the way, the Windows 8 Developer Preview site still happily talks about "Metro style app development,"; even though rumor has it that Microsoft is now banning all apps with the word "Metro" in their name from the Windows Store.']

(不分裂)

为什么startContainer不是更深(拆分)?像treeWalker一样?

以下是树步行者的代码:

var walker = document.createTreeWalker(document.body, NodeFilter.SHOW_ALL, function(node) {
    if (node.nodeType == 3) {
        return NodeFilter.FILTER_ACCEPT;
    } else if (node.offsetWidth && node.offsetHeight) {
        return NodeFilter.FILTER_SKIP;
    } else {
        return NodeFilter.FILTER_REJECT;
    }
}, false);

1 个答案:

答案 0 :(得分:2)

我想你已经选择了整个元素,比如其中一个链接。关键的事实是,从选择中获得的范围的startContainer不能保证是文本节点。

如果选择了整个元素,某些浏览器会将选择报告为跨越元素父节点的子节点。例如,对于跨越多个连续图像之一的选择,它是必不可少的。想象一下,选择只包含下面HTML中的第二个图像:

<div><img src="1.jpg"><img src="2.jpg"><img src="3.jpg"></div>

在这种情况下,所选范围将包含startContainerendContainer属性,这些属性引用<div>元素和startOffset 1和endOffset 2,代表在容器的childNodes属性中索引1和2处的子节点之间的范围拉伸。