[英]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.