获取textarea中的光标位置

本文介绍了一段使用JavaScript实现的功能,当用户在文本框中输入文本时,能够实时添加新文本到指定位置,并同时保存光标所在的位置。通过事件监听和DOM操作,简化了文本编辑的复杂性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<html>
<script>
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){
if (typeof (textBox.selectionStart) == "number") {
start = textBox.selectionStart;
end = textBox.selectionEnd;
}
else if(document.selection){
var range = document.selection.createRange();
if (range.parentElement().id == textBox.id) {
var range_all = document.body.createTextRange();
range_all.moveToElementText(textBox);
for (start = 0; range_all.compareEndPoints("StartToStart",
range) < 0; start++)
range_all.moveStart('character', 1);
for ( var i = 0; i <= start; i++) {
if (textBox.value.charAt(i) == '\n')
start++;
}
varrange_all = document.body.createTextRange();
range_all.moveToElementText(textBox);
for (end = 0; range_all.compareEndPoints('StartToEnd', range) < 0; end++)
range_all.moveStart('character', 1);
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>
<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="AddText" /></td>
</tr>
</table>
</form>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值