2012-05-15 80 views

回答

0

Textareas和文本輸入有一個不同的選擇API。它們具有selectionStartselectionEnd屬性,它們是textarea/input的value屬性內的字符偏移量。這些屬性在HTML5中已經標準化,並且由所有主流瀏覽器的當前版本實現,儘管IE < 9又具有不同的API。

2

您是否需要在textarea中獲取選定的文本?你可能會問的selectionStart和選定結束(在Internet Explorer中不存在,可與Firefox和Chrome)

Select some text below and then click the button:<br/> 
<textarea id="myTextarea" rows="5" cols="30"> 
Lorem ipsum dolor sit amet, 
consectetur adipiscing elit. 
</textarea> 
<button onclick="alert(getTextSelection())">alert text selection</button> 

<script type="text/javascript"> 
    function getTextSelection(){ 
     var field = document.getElementById("myTextarea"); 
     var startPos = field.selectionStart; 
     var endPos = field.selectionEnd;   
     var field_value = field.value; 
     var selectedText = field_value.substring(startPos,endPos); 
     return selectedText; 
    } 
</script> 

如果有多個文本域,你希望得到關於選擇輸出:

Select some text in either textarea:<br/> 
<textarea rows="5" cols="30" onselect="alert(getTextSelection(this))"> 
Lorem ipsum dolor sit amet, 
consectetur adipiscing elit. 
</textarea> 


<textarea rows="5" cols="30" onselect="alert(getTextSelection(this))"> 
fate it seems 
not without a sense of irony 
</textarea> 


<script type="text/javascript"> 
    function getTextSelection(field){   
     var startPos = field.selectionStart; 
     var endPos = field.selectionEnd;   
     var selectedText = field.value.substring(startPos,endPos); 
     return selectedText; 
    }  
</script> 

或者你還可以做一個按鈕,但通過使用全局變量:

Select some text in either textarea and click the button:<br/> 
<textarea rows="5" cols="30" onselect="window.selectedTextarea=this"> 
Lorem ipsum dolor sit amet, 
consectetur adipiscing elit. 
</textarea> 


<textarea rows="5" cols="30" onselect="window.selectedTextarea=this"> 
fate it seems 
not without a sense of irony 
</textarea> 



<button onclick="alert(getTextSelection())">alert text selection</button> 



<script type="text/javascript"> 
// warning: global variable: dirty!!! 
var selectedTextarea 

    function getTextSelection(){   
     var field = window.selectedTextarea; 
     var startPos = field.selectionStart; 
     var endPos = field.selectionEnd;   
     var selectedText = field.value.substring(startPos,endPos); 
     return selectedText; 
    }  
</script> 
+0

它時,你知道哪些textarea的集中工作,但如果有多個文本區域,這不能得到位置 –