2012-07-13 35 views
1

可能重複:
Understanding what goes on with textarea selection with JavaScript
Copy and paste the selected text to the clipboard using JavaScript捕獲在文本高亮文本的Mozilla瀏覽器中

我有點困惑,應該怎樣處理這個,我有一個文本框在這個區域中,我希望用戶能夠突出顯示文本框中的單詞。我需要捕捉突出顯示的單詞。它適用於除Mozilla之外的所有瀏覽器。

這裏我使用onkeydown事件。

var startPos = textComponent.selectionStart;   
var endPos = textComponent.selectionEnd; 

selected = textComponent.value.substring(startPos,endPos); 

這是我用它爲Mozilla的碼。它不工作。

請幫我

+0

該代碼工作的Mozilla瀏覽器,只要選擇實際存在。你什麼時候調用這個代碼?幾乎可以肯定的是,在代碼被調用的時候,選擇並不存在。 – 2012-07-13 11:00:28

回答

0
Howvever, I managed to fix this by this code. Please use this below coding for capturing the textbox selected value. 

<**head> 
    <script type="text/javascript"> 
     function GetSelectedText() { 
      var selText = ""; 
      if (window.getSelection) { // all browsers, except IE before version 9 
       if (document.activeElement && 
         (document.activeElement.tagName.toLowerCase() == "textarea" || 
         document.activeElement.tagName.toLowerCase() == "input")) 
       { 
        var text = document.activeElement.value; 
        selText = text.substring (document.activeElement.selectionStart, 
               document.activeElement.selectionEnd); 
       } 
       else { 
        var selRange = window.getSelection(); 
        selText = selRange.toString(); 
       } 
      } 
      else { 
       if (document.selection.createRange) { // Internet Explorer 
        var range = document.selection.createRange(); 
        selText = range.text; 
       } 
      } 
      if (selText !== "") { 
       alert (selText); 
      } 
     } 
    </script> 
</head> 
<body onmouseup="GetSelectedText()"> 
    Some text for selection. 
    <br /><br /> 
    <textarea>Some text in a textarea element.</textarea> 
    <input type="text" value="Some text in an input field." size="40"/> 
    <br /><br /> 
    Select some content on this page! 
</body>**