javascript获取textarea光标选择位置和内容方法(IE, Firefox)

在网上用baidu找了很久,找到的都是IE的方法,Firefox都不能用。 而且很多要用到<textarea>.focus()方法,用起来很不方便。
后来转用Google,搜了下"textarea cursor",第一个就有好方法。我根据最后一个家伙的comments,写了一个sample,应该还是挺好用的。
原文地址:http://weblogs.asp.net/skillet/archive/2005/03/24/395838.aspx

+展开
-HTML
<html>
<head>
<title>TEST</title>
<style>
body,td{
    font-family: verdana, arial, helvetica, sans-serif;
    font-size: 12px;
}

</style> 
<script type="text/javascript">
    var start=0;
    var end=0;
    function add(){        
        var textBox = document.getElementById("ta");
        var pre = textBox.value.substr(0, start);
        var post = textBox.value.substr(end);
        textBox.value = pre + document.getElementById("inputtext").value + post;
    }
    function savePos(textBox){
        //如果是Firefox(1.5)的话,方法很简单
        if(typeof(textBox.selectionStart) == "number"){
            start = textBox.selectionStart;
            end = textBox.selectionEnd;
        }
        //下面是IE(6.0)的方法,麻烦得很,还要计算上'\n'
        else if(document.selection){
            var range = document.selection.createRange();
            if(range.parentElement().id == textBox.id){
                // create a selection of the whole textarea
                var range_all = document.body.createTextRange();
                range_all.moveToElementText(textBox);
                //两个range,一个是已经选择的text(range),一个是整个textarea(range_all)
                //range_all.compareEndPoints()比较两个端点,如果range_all比range更往左(further to the left),则                //返回小于0的值,则range_all往右移一点,直到两个range的start相同。
                // calculate selection start point by moving beginning of range_all to beginning of range
                for (start=0; range_all.compareEndPoints("StartToStart", range) < 0; start++)
                    range_all.moveStart('character', 1);
                // get number of line breaks from textarea start to selection start and add them to start
                // 计算一下\n
                for (var i = 0; i <= start; i ++){
                    if (textBox.value.charAt(i) == '\n')
                        start++;
                }
                // create a selection of the whole textarea
                 var range_all = document.body.createTextRange();
                 range_all.moveToElementText(textBox);
                 // calculate selection end point by moving beginning of range_all to end of range
                 for (end = 0; range_all.compareEndPoints('StartToEnd', range) < 0; end ++)
                     range_all.moveStart('character', 1);
                     // get number of line breaks from textarea start to selection end and add them to end
                     for (var i = 0; i <= end; i ++){
                         if (textBox.value.charAt(i) == '\n')
                             end ++;
                     }
                }
            }
        document.getElementById("start").value = start;
        document.getElementById("end").value = end;
    }
</script> 
</head>
<body>
<form action="a.cgi">
<table border="1" cellspacing="0" cellpadding="0">
    <tr>
        <td>start: <input type="text" id="start" size="3"/></td>
        <td>end: <input type="text" id="end" size="3"/></td>
    </tr>
    <tr>
        <td colspan="2">
            <textarea id="ta" onKeydown="savePos(this)" 
                            onKeyup="savePos(this)" 
                            onmousedown="savePos(this)" 
                            onmouseup="savePos(this)" 
                            onfocus="savePos(this)" 
                            rows="14" cols="50">
</textarea>
        </td>
    </tr>
    <tr>
        <td><input type="text" id="inputtext" /></td>
        <td><input type="button" onClick="add()" value="Add Text"/></td>
    </tr>
</table>
</form>
</body>
</html>




+展开
-HTML
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=gb2312"> 
<meta name="GENERATOR" content="Microsoft FrontPage 4.0"> 
<meta name="ProgId" content="FrontPage.Editor.Document"> 
<title>光标位置</title> 
<style> 
INPUT{border: 1 solid #000000} 
BODY,TABLE{font-size: 10pt} 
</style>  
</head> 
<body> 
<table border="0" width="700" cellspacing="0" cellpadding="0"> 
<tr> 
<td width="479" rowspan="7"> 
点击 TextArea 实现光标定位 
<p> 
<textarea rows="7" cols="49" id="box" onclick=tellPoint()>我怕来不及我要抱着你,直到感觉你的绉纹有了岁月的痕迹,直到视线变得模糊直到不能呼吸 
为了你我愿意 
动也不能动也要看着你,直到感觉你的发线有了白雪的痕迹,直到肯定你是真的直到失去力气让我们形影不离 
如果全世界我也可以放弃,至少还有你值得我去珍惜而你在这里就是生命的奇迹 
也许全世界我也可以忘记,就是不愿意失去你的消息你掌心的痣我总记得在哪里 
我们好不容易我们身不由已,我怕时间太快不够将你看仔细,我怕时间太慢日夜担心失去你恨不得一夜之间白头永不分离 
</textarea> 
<script>

function movePoint() 

var pn = parseInt(pnum.value);

if(isNaN(pn)) 
return;

var rng = box.createTextRange();

rng.moveStart("character",pn);

rng.collapse(true);

rng.select();

returnCase(rng)

}

function tellPoint() 

var rng = event.srcElement.createTextRange();

rng.moveToPoint(event.x,event.y); 
rng.moveStart("character",-event.srcElement.value.length)

pnum.value = rng.text.length

returnCase(rng) 
}

function returnCase(rng) 

bh.innerText = rng.boundingHeight; 
bl.innerText = rng.boundingLeft; 
bt.innerText = rng.boundingTop; 
bw.innerText = rng.boundingWidth; 
ot.innerText = rng.offsetTop; 
ol.innerText = rng.offsetLeft; 
t.innerText = rng.text; 
}

function selectText(sp,ep) 

sp = parseInt(sp) 
ep = parseInt(ep)

if(isNaN(sp)||isNaN(ep)) 
return;

var rng = box.createTextRange();

rng.moveEnd("character",-box.value.length) 
rng.moveStart("character",-box.value.length)

rng.collapse(true);

rng.moveEnd("character",ep) 
rng.moveStart("character",sp)

rng.select();

returnCase(rng); 
}

var rg = box.createTextRange();

function findText(tw) 

if(tw==""
return;

var sw = 0;

if(document.selection) 

sw = document.selection.createRange().text.length; 
}

rg.moveEnd("character",box.value.length);

rg.moveStart("character",sw);

if(rg.findText(tw)) 

rg.select();

returnCase(rg); 
}

if(rg.text!=tw) 

alert("已经搜索完了"
rg = box.createTextRange() 
}

}

</script>  
</p> 
<p></p> 
光标位置:<input type="text" value="0" id="pnum" size="8"> <input type="button" onclick="movePoint()" value="移动光标到指定位置"> 
<p></p> 
选择指定范围:<input type="text" size="9" id="sbox"> -- <input type="text" size="9" id="ebox"> <input type="button" onclick="selectText(sbox.value,ebox.value)" value="选择"> 
<p></p> 
选择查找字符 :<input type="text" value="" id="cbox" size="8"> <input type="button" onclick="findText(cbox.value)" value="查找下一个并选择">

</td> 
<td width="217">boundingHeight:&nbsp;<span id="bh"></span></td> 
</tr> 
<tr> 
<td width="217">boundingWidth:&nbsp;<span id="bw"></span></td> 
</tr> 
<tr> 
<td width="217">boundingTop:&nbsp;<span id="bt"></span></td> 
</tr> 
<tr> 
<td width="217">boundingLeft:&nbsp;<span id="bl"></span></td> 
</tr> 
<tr> 
<td width="217">offsetLeft:&nbsp;<span id="ol"></span> </td> 
</tr> 
<tr> 
<td width="217">offsetTop:&nbsp;<span id="ot"></span> </td> 
</tr> 
<tr> 
<td width="217">text:&nbsp;<span style="position: absolute; z-index: 10" id="t"></span> </td> 
</tr> 
</table> 
</body>

</html>


+展开
-HTML
<!!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">> 
<HTML> 
<HEAD> 
<TITLE> 兼容firefox下选择textarea文字的js代码_脚本之家_www.jb51.net </TITLE> 
<META NAME="Generator" CONTENT="EditPlus"> 
<META NAME="Author" CONTENT=""> 
<META NAME="Keywords" CONTENT=""> 
<META NAME="Description" CONTENT=""> 
<script type="text/javascript"> 
    function getSelectedText(){ 
        var selectedText; 
        var textField=document.getElementById('inputTextarea'); 
        if(window.getSelection) selectedText=getTextFieldSelection(textField);//getTextFieldSelection(document.getElementById("inputTextArea")); 
        else selectedText=document.selection.createRange().text; 
            alert(selectedText); 
    }

    function getTextFieldSelection(e){ 
        //var oEvent=arguments.callee.caller.arguments[0]; 
        if(e.selectionStart != undefined && e.selectionEnd != undefined) 
            return e.value.substring(e.selectionStart,e.selectionEnd); 
        else return ""
    } 
</script>  
<style type="text/css"> 
    ul{ 
        list-style:none; 
    }
 
</style>  
</HEAD>

<BODY> 
    <ul> 
        <li>兼容firefox下选取textarea文本的方法</li> 
        <li><textarea id="inputTextarea" rows="6" cols="50"/>千万别相信我说的事情,我从来就没有这么勇敢过,这么壮烈过。我不断发誓要老老实实讲故事,可是说实话的愿望有多强烈,受到的各种干扰就有多大。我悲哀地发现根本就无法还原真相。记忆总是被我的情感改头换面,并随之捉弄我,背叛我。把我搞得头昏脑胀,真假难辩。</textarea></li> 
        <li><button onclick="getSelectedText();">获取选中的文字段</button></li> 
    </ul> 
</BODY> 
</HTML>



本文来自: 脚本之家(www.jb51.net) 详细出处参考:http://www.jb51.net/article/14735.htm

加支付宝好友偷能量挖...


评论(0)网络
阅读(148)喜欢(0)JavaScript/Ajax开发技巧