|
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)的話,方法很簡(jiǎn)單
if(typeof(textBox.selectionStart) == "number"){
start = textBox.selectionStart;
end = textBox.selectionEnd;
}
//下面是IE(6.0)的方法,麻煩得很,還要計(jì)算上'/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);
//兩個(gè)range,一個(gè)是已經(jīng)選擇的text(range),一個(gè)是整個(gè)textarea(range_all)
//range_all.compareEndPoints()比較兩個(gè)端點(diǎn),如果range_all比range更往左(further to the left),則 //返回小于0的值,則range_all往右移一點(diǎn),直到兩個(gè)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
// 計(jì)算一下/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;
}
下面是在頁(yè)面中調(diào)用js代碼的方法:
<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>
此代碼的原文是:http://blog.csdn.NET/liujin4049/archive/2006/09/19/1244065.ASPx,在此謝過!
這段js代碼同時(shí)支持IE和Firefox,甚是精彩,可見此人js功力深厚啊,呵呵。
Btw:聽說(shuō)Firefox現(xiàn)在的市場(chǎng)占有率已經(jīng)達(dá)到17%了,而IE8也快出來(lái)了,瀏覽器之間又會(huì)掀起一場(chǎng)你死我活的爭(zhēng)斗,而這種爭(zhēng)斗可以使瀏覽器的解析標(biāo)準(zhǔn)會(huì)越來(lái)越規(guī)范,我們寫代碼也會(huì)越來(lái)越省事,這實(shí)在是一件值得高興的事。
JavaScript技術(shù):用javascript獲取textarea中的光標(biāo)位置,轉(zhuǎn)載需保留來(lái)源!
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請(qǐng)第一時(shí)間聯(lián)系我們修改或刪除,多謝。