2012-02-07 11 views
2

私は自分のページでテキストを選択してボタンをクリックすると、JavaScriptを介してこのテキストを取得します。テキスト選択が機能していない

function getSelText() 
    { 

     var t = ''; 
     if(window.getSelection){ 
      t = window.getSelection(); 
     }else if(document.getSelection){ 
      t = document.getSelection(); 
     }else if(document.selection){ 
      t = document.selection.createRange().text; 
     } 
     return t; 
    } 

私はこの機能を持っていますが、機能しません。

self.Copy = function() { 
     alert(getSelText()); 
    } 

コピー機能は動作していますが、警告の結果は常に空です。

+0

は、選択を解除しませんが、何か他のものをクリックすると、選択解除します - ブラウザの基本的な振る舞いを。 –

答えて

0

このコードは私のために働いている:ボタンをクリックする

<html> 
<head> 
    <script type="text/javascript"> 
     function TestSelection() { 
      if (window.getSelection) { 
       var selectionRange = window.getSelection();           
       alert ("The text content of the selection:\n" + selectionRange.toString()); 
      } 
      else { 
       if (document.selection.type == 'None') { 
        alert ("No content is selected, or the selected content is not available!"); 
       } 
       else { 
        var textRange = document.selection.createRange(); 
        alert ("The text content of the selection:\n" + textRange.text); 
       } 
      } 
     } 
    </script> 
</head> 
<body> 
    Select some text or <button>element</button>, or do not select anything, before you click on the button below. 
    <br /><br /> 
    <button onclick="TestSelection();">Test the selection!</button> 
</body> 
</html> 
関連する問題