2010-08-24 44 views
1

我正在嘗試讀取文本區域內選定文本的值。這裏是我的代碼:Javascript:從IE8中的Textarea中獲取選定文本

function readSelected(id) 
{ 
    textarea = document.getElementById(id); 
    if (document.selection) 
    { //Code for IE 
     textarea.focus(); 
     sel = document.selection.createRange(); 
     alert(sel.text); 
    } 
    else 
    { // Code for Mozilla Firefox 
     var len = textarea.value.length; 
     var start = textarea.selectionStart; 
     var end = textarea.selectionEnd; 

     var scrollTop = textarea.scrollTop; 
     var scrollLeft = textarea.scrollLeft; 

     sel = textarea.value.substring(start, end); 

     alert(sel); 
    } 
} 

HTML:

<textarea id="txt1" rows="10"></textarea> 
<a onclick="readSelected('txt1');">Get Selected</a> 

當您單擊該按鈕時,應該會出現一個彈出窗口告訴你選定的文本是什麼。

該代碼在Firefox中工作,但我無法讓它在IE8中工作。

回答

3

問題是單擊<a>元素會破壞選擇。你可以使用,而不是不能選擇的按鈕:

<input type="button" value="get" onclick="readSelected('txt1');" unselectable="on"> 

還有其他一些小問題與您的代碼

  1. 你應該聲明所有的變量,否則,他們最終泄漏到了全球範圍。 seltextarea是這裏的罪犯。
  2. scrollTopscrollLeft是多餘的。
  3. 您應該首先測試selectionStartselectionEnd屬性,因爲它們是標準(HTML 5指定它們,IE 9將支持它們)。

這裏是我的改寫版本:

function readSelected(id) { 
    var sel = "", el = document.getElementById(id); 
    if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") { 
     sel = el.value.slice(el.selectionStart, el.selectionEnd); 
    } else if (document.selection && document.selection.createRange) { 
     el.focus(); 
     sel = document.selection.createRange().text; 
    } 
    alert(sel); 
} 
+0

感謝您的回覆。代碼更正讚賞!假設我按照您的建議做了必要的JS更正,是否有任何理由不像其他答覆者所建議的那樣使用onmousedown? – Morgan 2010-08-24 17:24:16

+0

我看不到。 – 2010-08-24 17:26:06

2

你與onmousedown代替onclick試試?

+0

它與'onmousedown'一起使用。有沒有任何理由使用onclick vs onmousedown;除了它的作品?正如蒂姆所建議的那樣,我不反對把''改爲''。 – Morgan 2010-08-24 17:21:26

+0

'onmousedown'如果在釋放鼠標時發生的文本「取消選擇」之前觸發。 – 2010-08-24 21:20:16

相關問題