document.selection.createRange()

本文介绍了如何在HTML编辑器中利用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>



 

转载于:https://www.cnblogs.com/bullfighter/archive/2011/09/22/2185203.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值