0

我想在页面中生成一个节点数组,其中将包含 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是什么?

这是tree walker的代码:

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);
4

1 回答 1

2

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

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

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

在这种情况下,所选范围将具有引用元素和startContainer1和2 的属性,表示容器属性中索引 1 和 2 处的子项之间的范围拉伸。endContainer<div>startOffsetendOffsetchildNodes

于 2012-10-02T13:24:43.117 回答