【发布时间】:2021-06-12 08:55:31
【问题描述】:
我的问题是关于这个功能: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 在span 元素上返回true。这是预期的行为吗? the span element supposed to be selected whenever the img is selected, right?
【问题讨论】:
-
请edit您的问题在问题本身中包含所有相关代码,而不仅仅是在像codesandbox.io这样的外部网站上。请阅读How to Ask。
-
你好,亚历克斯!请花一些时间edit您的问题并访问How to Ask或访问Help Center。
标签: javascript selection selection-api