【问题标题】:Selection.containsNode() returning true even when Node is not contained即使不包含 Node,Selection.containsNode() 也会返回 true
【发布时间】:2020-12-11 17:28:01
【问题描述】:

来自https://developer.mozilla.org/en-US/docs/Web/API/Selection/containsNode

参数

节点 在选择中查找的节点。部分包含可选 当为 true 时,当节点的一部分是选择的一部分时, containsNode() 返回 true。当为 false 时, containsNode() 仅返回 true 当整个节点是选择的一部分时。如果未指定,则 使用默认值 false。

【问题讨论】:

    标签: dom selection


    【解决方案1】:

    我写了一个解决方法(在打字稿中)

    function getRangePartiallySelectedNodes(
      selection: Selection,
      parent: Node
    ): Node[] {
      return [
        // containsNode doesn't work as expected, always gives partial nodes
        ...(selection.containsNode(parent, true) ? [parent] : []),
        ...(parent.hasChildNodes()
          ? Array.from(parent.childNodes)
              .map((node) => getRangePartiallySelectedNodes(selection, node))
              .flat()
          : []),
      ];
    }
    
    function isAncestor(node: Node, possibleAncestor: Node): boolean {
      if (!node || !node.parentNode) return false;
      return (
        node.parentNode.isSameNode(possibleAncestor) ||
        isAncestor(node.parentNode, possibleAncestor)
      );
    }
    
    export function selectionContainsNodes(
      sel: Selection,
      // limitation: the selection must be within the elementEditing node
      elementEditing: HTMLElement
    ): boolean {
      if (sel.isCollapsed) return false;
      const nodes = getRangePartiallySelectedNodes(sel, elementEditing);
      // sel.anchorNode and sel.focusNode may be parents of the actual selection start instead of the selection themselves
      return nodes.some(
        (node) =>
          !isAncestor(sel.anchorNode, node) &&
          !node.isSameNode(sel.anchorNode) &&
          !isAncestor(sel.focusNode, node) &&
          !node.isSameNode(sel.focusNode)
      );
    

    【讨论】:

      猜你喜欢
      • 2023-04-09
      • 1970-01-01
      • 2018-05-29
      • 2012-09-26
      • 2012-01-14
      • 2021-02-08
      • 1970-01-01
      • 2020-04-08
      • 1970-01-01
      相关资源
      最近更新 更多