我的问题是关于这个功能: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
span
img