如何解决Javascript 选择 API :: containsNode() 在选择 span 元素时不返回 true
我的问题是关于这个函数:https://developer.mozilla.org/en-US/docs/Web/API/Selection/containsNode 我创建了这个沙箱: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);
});
我不明白为什么我应该在图像前后至少选择一个字符,以便 containsNode
在 true
元素上返回 span
。这是预期的行为吗?只要选择img
,就会选择跨度元素,右?
解决方法
这是预期的行为。
来自specification for the Selection API:
containsNode()
方法
该方法必须返回 false
如果上下文
对象为空或者如果节点的根不是与之关联的文档
上下文对象。
否则,如果 allowPartialContainment
为 false
,则该方法必须返回
true
当且仅当其范围的开始在之前或在视觉上
相当于节点和的第一个边界点
范围在最后一个边界点之后或在视觉上等同于
节点。
如果 allowPartialContainment 为 true
,则该方法必须返回 true
,如果并且
仅当其范围的开始在之前或在视觉上等同于
节点中的第一个边界点或其范围的末端在或之后
视觉上等同于节点中的最后一个边界点。
containsNode()
的接口是 defined as:
boolean containsNode(Node node,optional boolean allowPartialContainment = false);
如果您还希望将仅部分包含的节点视为选择的一部分,则必须为 true
参数提供 allowPartialContainment
:
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
是一个空元素(没有内容),因此不能仅部分包含在选择中。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。