原生JavaScript 处理 动态光标 插入 文字
鼠标点哪插哪
code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
</head>
<body>
<input name="" id="txt1" cols="30" rows="10" :placeholder= /><br>
<input type="text" name="" id="txt2">
<input type="button" value="添加" id="btn">
<input type="button" value="获取内容" id="btn1" οnclick="get()">
<div id="thistext"></div>
<script type="text/javascript">
window.onload = function () {
var oTxt1 = document.getElementById("txt1");
var oTxt2 = document.getElementById("txt2");
var oBtn = document.getElementById("btn");
oBtn.onclick = function () {
getValue("txt1", oTxt2.value);
}
}
</script>
<script type="text/javascript">
function get() {
document.getElementById("thistext").innerHTML = document.getElementById("txt1").value;
console.log(document.getElementById("txt1").value)
}
//了在IE、Firefox、Opera等主流浏览器的获取光标位置(getCursortPosition)以及设置光标位置(setCursorPosition)的函数
//objid:textarea的id str:要插入的内容
function getValue(objid, str) {
var myField = document.getElementById("" + objid);
//IE浏览器
if (document.selection) {
myField.focus();
sel = document.selection.createRange();
sel.text = str;
sel.select();
}
//火狐/网景 浏览器
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) + str + myField.value.substring(endPos, myField.value.length);
//如果滚动条高度大于0
if (restoreTop > 0) {
// 返回
myField.scrollTop = restoreTop;
}
myField.focus();
myField.selectionStart = startPos + str.length;
myField.selectionEnd = startPos + str.length;
}
else {
myField.value += str;
myField.focus();
}
}
</script>
</body>
</html>
评论 (0)