实例如下所示:
//IE 浏览器
if (document.selection) {
myField.focus();
sel = document.selection.createRange();
sel.text = myValue;
sel.select();
}
if (document.selection) {
myField.focus();
sel = document.selection.createRange();
sel.text = myValue;
sel.select();
}
//FireFox、Chrome等
else if (myField.selectionStart || myField.selectionStart == '0') {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
// 保存滚动条
var restoreTop = myField.scrollTop;
myField.value = myField.value.substring(0,startPos) + myValue + myField.value.substring(endPos,myField.value.length);
if (restoreTop > 0) {
myField.scrollTop = restoreTop;
}
myField.focus();
myField.selectionStart = startPos + myValue.length;
myField.selectionEnd = startPos + myValue.length;
} else {
myField.value += myValue;
myField.focus();
}
}
<textarea id="textarea" style="width: 386px; height: 260px">
以上这篇JS实现在文本指定位置插入内容的简单示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持编程之家。
原文链接:https://www.f2er.com/js/34563.html