document.selection.createRange()

document.selection.createRange() 根据当前文字选择返回 TextRange 对象,或根据控件选择返回 ControlRange 对象。

配合 execCommand,在 HTML 编辑器中很有用,比如:文字加粗、斜体、复制、粘贴、创建超链接等。

举例1:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>document.selection 的 createRange</title>
</head>
<body>

<div>请选中这里的部分文字。</div>
<div><input type="button" value="加粗" onclick="javascript:Bold();" /></div>
<script type="text/javascript" language="javascript">
<!--
function Bold()
{
    var r = document.selection.createRange();
    r.execCommand("Bold");
}
-->
</script>

</body>
</html>

 

举例2:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script>
var selection;
function alertSelection()
{
    //***** IE下面
    try {
        selection=document.selection.createRange().text;
    }
    //***** 其他浏览器下面
    catch(e) {
        selection=document.getSelection();
    }
    if(selection!="")
    {
        alert(selection);
        selection="";
    }
}
</script>
</head>
<body>
<ul>
    <li onmouseup="alertSelection()">中华人民共和国</li>
    <li onmouseup="alertSelection()">美利坚合众国</li>
    <li onmouseup="alertSelection()">大不列颠联合王国</li>
</ul>
</body>
</html>

举例3:(参考)有错误

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script>
function alertSelection(Xelement)
{

   
try {
        alert(document.selection.createRange().text);
    }
   
catch(e) {
       
var textarea1=document.getElementById("textarea1");
        alert(textarea1.value.substring(textarea1.selectionStart,textarea1.selectionEnd));
    }
}
</script>
</head>
<body>
<ul>
    <li onmousedown="alertSelection(this)">中华人民共和国</li>
    <li onmousedown="alertSelection(this)">美利坚合众国</li>
    <li onmousedown="alertSelection(this)">大不列颠联合王国</li>
</ul>
<textarea id="textarea1"></textarea>
</body>
</html>



 

posted on 2011-09-22 15:55  老牛骑士  阅读(1654)  评论(0)    收藏  举报

导航