2012-02-07 65 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

點擊一個按鈕,就不會清除選擇,但點擊任何東西都不會清除選擇 - 瀏覽器的基本行爲。 – 2012-02-07 15:29:12

回答

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>