JAVAScript document.selection.createRange方法

document.selection.createRange() 方法根據當前選擇文字返回 TextRange 對象,或根據選擇控件返回 ControlRange 對象。
配合 execCommand,在 HTML 編輯器中可以完成很多事情,比如文字加粗、斜體、復制、粘貼、創建超鏈接等。
 
實例一:
<textarea cols=50 rows=15>
測試內容!</textarea>
<input type=button value=選擇字後點擊我看看 onclick=alert(document.selection.createRange().text)>
 
實例二:
<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>

作者“葉孤城”
 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *