2016-04-26 10 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> 

警告(選択.length);いつも誰かがこれで私を助けることができますか?ありがとうございました。範囲には選択したテキストが含まれます。

+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

関連する問題