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);
});

我不明白为什么我应该在图像前后至少选择一个字符,以便 containsNodetrue 元素上返回 span。这是预期的行为吗?只要选择img,就会选择跨度元素,右?

解决方法

这是预期的行为。

来自specification for the Selection API

containsNode() 方法

该方法必须返回 false 如果上下文 对象为空或者如果节点的根不是与之关联的文档 上下文对象。

否则,如果 allowPartialContainmentfalse,则该方法必须返回 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 是一个空元素(没有内容),因此不能仅部分包含在选择中。