Javascript window.getSelection() 长度为 0,而使用 querySelector

Javascript window.getSelection() length 0 while using querySelector

本文关键字:querySelector getSelection window Javascript      更新时间:2023-09-26

我正在尝试使用 window.getSelection.getRangeAt(0) 获取所选文本这是我的代码:

<!DOCTYPE html>
<html>
    <head>
        <script>
          function Selected(){
            var range = window.getSelection().getRangeAt(0);
              alert(range);
            content = range.cloneContents();
            var select = content.querySelectorAll('span');
            alert(select.length);
          }
          </script>
    </head>
    <body >
        <span style="font-size:45px"  onmouseup="Selected()" id="idNo1">This is some text</span>
    </body>
</html>

警报(选择长度);总是 0 有人可以帮助我解决这个问题。谢谢。但范围包含所选文本。

你不能这样做

来获取选定的字符串长度吗?alert(range) 正在执行 range.toString()

<!DOCTYPE html>
<html>
    <head>
        <script>
          function Selected(){
            var range = window.getSelection().getRangeAt(0);
              // to get the text ( it does range.toString() )
              alert(range);
              // to get the text length
              alert(range.toString().length);
              // to get the id of the startNode
              alert(range.startContainer.parentNode.id);
          }
          </script>
    </head>
    <body >
        <span style="font-size:45px"  onmouseup="Selected()" id="idNo1">This is some text</span>
    </body>
</html>

答案和一些有用的相关位:

所选文本

window.getSelection().toString();//pa'rtially selected tex't.
window.getSelection().toString().length;//20, length of the selected text.

锚节点(开始初始文本拖动的位置)中的文本可以位于左侧右侧

window.getSelection().anchorNode;//Node text, NOT selection text.
window.getSelection().anchorNode.length;//Length of node's text, not selection.

焦点节点(文本初始拖动结束的位置)中的文本可以位于左侧右侧:

window.getSelection().focusNode;//Node text, NOT selection text.
window.getSelection().focusNode.length;//Length of node's text, not selection.

所选文本的共同祖先(实际上是parentNode):

window.getSelection().getRangeAt(0).commonAncestorContainer

删除所选文本:

window.getSelection().deleteFromDocument();