2009-06-29 43 views
2

我不熟悉這些屬性,如何通過JavaScript獲取textarea元素內的選定文本?

有人可以提供一個簡單的演示嗎?

我需要它沒有任何圖書館。

+3

堆棧溢出存檔 - http://stackoverflow.com/questions/717224/how-to-get-selected-text-in-textarea - http://stackoverflow.com/questions/275761/how-從文本框控制與js --- **提示**:在問一個問題之前,看看谷歌:`站點:stackoverflow.com JavaScript獲取選定文本內textarea`只返回相關材料來自stackoverflow.com。或者你可以在地址欄中輸入同樣的東西,去第一個結果。給它一個鏡頭,輸入到你的地址欄中:`?site:stackoverflow.com javascript獲取textarea內選定的文本 – Sampson 2009-06-29 12:35:29

回答

6
<script type="text/javascript"> 

     function ShowSelectionInsideTextarea() 
{ 
var textComponent = document.getElementById('mytextarea'); 

    var selectedText; 
    // IE version 
    if (document.selection != undefined) 
    { 
    textComponent.focus(); 
    var sel = document.selection.createRange(); 
    selectedText = sel.text; 
    } 
    // Mozilla version 
    else if (textComponent.selectionStart != undefined) 
    { 
    var startPos = textComponent.selectionStart; 
    var endPos = textComponent.selectionEnd; 
    selectedText = textComponent.value.substring(startPos, endPos) 
    } 
    alert("You selected: " + selectedText); 

} 
</script> 
相關問題