2016-04-26 69 views
1

我试图让使用选定的文本window.getSelection.getRangeAt(0) 这是我的代码:的Javascript window.getSelection()长度为0,而使用querySelector

<!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

是啊,我知道。当我选择“这是一些文本”范围包含但不能使用querySelecctorAall –

回答

1

难道你不能这样做,以获得选定的字符串长度? 警报(范围)做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> 
+0

我们是否也可以使用此方法获取所选文本的ID? – Jois

+0

你可以通过range.startContainer.parentNode –

+0

你能解释一下吗?需要它非常糟糕 – Jois