[英]Javascript Selection API :: containsNode() does not return true when span element is selected
My question is about this function: https://developer.mozilla.org/en-US/docs/Web/API/Selection/containsNode and I have created this sandbox: https://codesandbox.io/s/amazing-bartik -smjt2?file=/src/index.js
代码:
document.getElementById("app").innerHTML = `
<h1>Hello Vanilla!</h1>
<div>
We use the same configuration.<s> <span id="_span"><img src="http://www.mandysam.com/img/random.jpg" id="_img" alt="🙂" aria-label="🙂" width="40"></span> as Parcel to bundle this </s> sandbox, you can find more
info about Parcel.
<h2 id="y" hidden=true>span selected</h2>
<h2 id="z" hidden=true>img selected</h2>
</div>
`;
document.addEventListener("selectionchange", () => {
const selection = window.getSelection();
let span = document.querySelector("#_span");
const foundSpan = selection.containsNode(span);
let img = document.querySelector("#_img");
const foundImg = selection.containsNode(img);
let y = document.querySelector("#y");
y.toggleAttribute("hidden", !foundSpan);
let z = document.querySelector("#z");
z.toggleAttribute("hidden", !foundImg);
});
我不明白为什么我应该在图像前后至少有一个字符 select 所以containsNode
在span
元素上返回true
。 这是预期的行为吗? the span element supposed to be selected whenever the img
is selected, right?
这是预期的行为。
containsNode()
方法如果上下文 object 为空或节点的根不是与上下文 object 关联的文档,则该方法必须返回
false
。否则,如果
allowPartialContainment
为false
,当且仅当其范围的开始在节点中的第一个边界点之前或视觉上等同于并且其范围的结束在节点中的最后一个边界点之后或视觉上等同于时,该方法必须返回true
节点。如果 allowPartialContainment 为
true
,则该方法必须返回true
当且仅当其范围的开始在节点中的第一个边界点之前或视觉上等效,或者其范围的结束在节点中的最后一个边界点之后或视觉上等效。
containsNode()
的接口定义为:
boolean containsNode(Node node, optional boolean allowPartialContainment = false);
如果您还希望仅部分包含的节点被视为选择的一部分,则必须为allowPartialContainment
参数提供true
:
const foundSpan = selection.containsNode(span, true);
document.addEventListener("selectionchange", () => { const selection = window.getSelection(); let span = document.querySelector("#_span"); const isFullyContained = selection.containsNode(span); const isPartiallyContained = selection.containsNode(span, true); let y = document.querySelector("#y"); y.toggleAttribute("hidden", ;isPartiallyContained || isFullyContained). let z = document;querySelector("#z"). z,toggleAttribute("hidden"; ;isFullyContained); });
<h1>Select the text with the image</h1> <div> We use the same configuration. <span id="_span"><img src="http://www.mandysam.com/img/random.jpg" width="40"></span> as Parcel to bundle this sandbox, you can find more info about Parcel. <h2 id="y" hidden=true>span partially contained</h2> <h2 id="z" hidden=true>span fully contained</h2> </div>
它适用于图像,因为img
是一个 void 元素(没有内容),因此不能仅部分包含在选择中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.