gpt4 book ai didi

javascript - Range startContainer 不是最深的节点

转载 作者:行者123 更新时间:2023-12-02 19:19:42 25 4
gpt4 key购买 nike

我想在页面中生成一个节点数组,其中包含范围的所有可能的 startContainer。

我尝试使用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 不更深(分割)?就像树行者一样?

这是树步行者的代码:

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

最佳答案

我想您已经选择了整个元素,例如其中一个链接。关键的事实是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 处的子级之间的范围延伸属性。

关于javascript - Range startContainer 不是最深的节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12691010/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com