document.selection.createRange() 根據當前文字選擇返回 TextRange 對象,或根據控件選擇返回 ControlRange 對象。
配合 execCommand,在 HTML 編輯器中很有用,比如:文字加粗、斜體、復制、粘貼、創建超鏈接等。
實例一:
<textarea cols=50 rows=15> 哈哈。我們都是新生來得。大家都來相互幫助呀。這樣我們才能進步,我們才能賺大錢!</textarea> <input type=button value=選擇字后點擊我看看 onclick=alert(document.selection.createRange().text)> < /form>
實例二:
<body> <textarea name="textfield" cols="50" rows="6">就是現在文本域里有一段文字,當你選種其中幾個字后點擊一個按鈕或者鏈接會彈出一個對話框,對話框的信息就是你選中的文字 哪位老大能解決的呀?請多多幫忙!!!謝謝 </textarea> <input type="button" value="showSelection" onclick="alert(document.selection.createRange().text)"> <input type="button" value="showclear" onclick="alert(document.selection.clear().text)"> <input type="button" value="showtype" onclick="alert(document.selection.type)"> <textarea name="textfield" cols="50" rows="6" onselect="alert(document.selection.createRange().text)">就是現在文本域里有一段文字,當你選種其中幾個字后點擊一個按鈕或者鏈接會彈出一個對話框,對話框的信息就是你選中的文字 哪位老大能解決的呀?請多多幫忙!!!謝謝 </textarea>
</body>
實例三:選中Input中的文本
<SCRIPT LANGUAGE="JavaScript"> <!-- function test2() { var t=document.getElementById("test") var o=t.createTextRange() alert(o.text) o.moveStart("character",2) alert(o.text) o.select() } //--> </SCRIPT> <input type='text' id='test' name='test'><input type=button onclick='test2()' value='test' name='test3'> 對textarea中的內容,進行選中后,加效果
<script language="JavaScript"> <!-- function bold(){ Qr=document.selection.createRange().text; if(!Qr || document.selection.createRange().parentElement().name!='description') { txt=prompt('Text to be made BOLD.',''); if(txt!=null && txt!='') document.form1.description.value+=''+txt+''; } else{ document.selection.createRange().text=''+document.selection.createRange().text+''; document.selection.empty(); } } //--> </script> < input type="button" value="加粗" onclick="bold();" /> <textarea name="description" style="width: 436px; height: 296px">選中我,點擊加粗</textarea>
實例四:javascript捕獲到選中的網頁中的純文本內容
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>鼠標取詞</title> <script> function getSel() { var t=window.getSelection?window.getSelection():(document.getSelection?document.getSelection():(document.selection?document.selection.createRange().text:"")) document.forms[0].selectedtext.value = t; } </script></head> <body onmouseup="getSel()"> <form> <textarea name="selectedtext" rows="5" cols="50"></textarea> </form> 以上的代碼可以捕獲到選中的網頁中的純文本內容(不含HTML標簽) 如果想獲得包含html的內容,將document.selection.createRange().text改成document.selection.createRange().htmlText </body> </html>
|