当前位置: 代码迷 >> JavaScript >> JAVAScript document.selection.createRange步骤
  详细解决方案

JAVAScript document.selection.createRange步骤

热度:478   发布时间:2012-10-20 14:12:48.0
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>

  相关解决方案