【问题标题】:document.getSelection with carriage return in selectiondocument.getSelection 在选择中带有回车符
【发布时间】:2021-10-30 03:50:35
【问题描述】:

我尝试了很多不同的东西,但不知所措。下面的代码说明了这个问题。我有一个可编辑的元素。

如果我选择一段文本,则 Selection.anchorNode 是一个#text 节点。

如果在选择段落时我在段落前包含回车符,则 Selection.anchorNode 是包含 span 元素。

我需要知道的是从 span 元素的 innerText 值开始的偏移量是多少。 When a carriage return IS NOT included in the selection, I am able simply to analyze the sibling nodes of the anchorNode. But when a carriage return IS included in the selection, I don't seem to have the information to achieve this.

任何关于我缺少什么的指导将不胜感激。

function showResult() {
  let sel = document.getSelection();
  document.getElementById("output").textContent ="document.getSelection().anchorNode.nodeName: " +  sel.anchorNode.nodeName;
}
document.getElementById("textContainer").innerText = "This is the first paragraph\n\nSelecting this paragraph with and without the preceding carriage return yields very different anchorNodes";
#textContainer {
  position: relative;
  display: inline-block;
  width: 400px;
  height: 100px;
  border: 1px solid steelblue;
  margin: 5px;
}

#output {
  position: relative;
  width: 400px;
  height: 100px;
  border: 1px solid steelblue;
  margin: 5px;
}
<div>
    <span id="textContainer" contenteditable="true"></span>
</div>
<input  type="button" onclick="showResult()" value="Write selection object to console" />
<div id="output">
</div>

【问题讨论】:

    标签: javascript selection dom-selection


    【解决方案1】:

    在选择回车时浏览器似乎返回父节点,因此您可以在这种情况下使用if 条件:

    sel.anchorNode.hasChildNodes()?sel.anchorNode.childNodes[0].nodeName:sel.anchorNode.nodeName
    

    function showResult() {
      let sel = document.getSelection();
      document.getElementById("output").textContent ="document.getSelection().anchorNode.nodeName: " +  (sel.anchorNode.hasChildNodes()?sel.anchorNode.childNodes[0].nodeName:sel.anchorNode.nodeName);
    }
    document.getElementById("textContainer").innerText = "This is the first paragraph\n\nSelecting this paragraph with and without the preceding carriage return yields very different anchorNodes";
    #textContainer {
      position: relative;
      display: inline-block;
      width: 400px;
      height: 100px;
      border: 1px solid steelblue;
      margin: 5px;
    }
    
    #output {
      position: relative;
      width: 400px;
      height: 100px;
      border: 1px solid steelblue;
      margin: 5px;
    }
    <div>
        <span id="textContainer" contenteditable="true"></span>
    </div>
    <input  type="button" onclick="showResult()" value="Write selection object to console" />
    <div id="output">
    </div>

    【讨论】:

    • 啊,是的,这让我明白了。当节点有子节点时,Selection.anchorOffset 是 childNodes 数组的索引,它为我提供了计算从跨度的 innerText 开始的选择的偏移量所需的内容。谢谢!
    猜你喜欢
    • 2017-06-01
    • 1970-01-01
    • 2017-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-10
    • 2015-05-19
    • 1970-01-01
    相关资源
    最近更新 更多