<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<meta charset="utf-8" />
<head>
<title></title>
</head>
<body>
<textarea id="test" />改个需求。</textarea>
<input type="button" onclick="tt('呵呵')" value="aa" />
<script type="text/javascript">
function tt(val) {
var val = val;
var test = document.getElementById('test');
if(document.selection) { //ie 8,9,10
test.focus();
sel = document.selection.createRange();
sel.text = val;
test.focus();
} else {
if(test.selectionStart || test.selectionStart == '0') { //光标开始的位置
var startPos = test.selectionStart;
var endPos = test.selectionEnd;
var scrollTop = test.scrollTop;
console.log(startPos)
test.value = test.value.substring(0, startPos) + val + test.value.substring(endPos, test.value.length);
test.focus();
test.selectionStart = startPos + val.length; //设置鼠标开始位置
test.selectionEnd = startPos + val.length; //设置鼠标结束位置
test.scrollTop = scrollTop; //插入的文字显示在滚动条内
} else {
test.value += val;
test.focus();
}
}
}
</script>
</body>
</html>
可参考 https://blog.csdn.net/mafan121/article/details/78519348