支持文本框input 和textarea等向光标位置插入内容
insertText(obj, str) {
if (document.selection) {
var sel = document.selection.createRange();
sel.text = str;
} else if (typeof obj.selectionStart === 'number' && typeof obj.selectionEnd === 'number') {
var startPos = obj.selectionStart,
endPos = obj.selectionEnd,
cursorPos = startPos,
tmpStr = obj.value;
obj.value = tmpStr.substring(0, startPos) + str + tmpStr.substring(endPos, tmpStr.length);
cursorPos += str.length;
obj.selectionStart = obj.selectionEnd = cursorPos;
//选择焦点的位置
obj.setSelectionRange(obj.selectionStart, obj.selectionStart);
} else {
obj.value += str;
}
//重新获得焦点
obj.focus();
}
使用方法
var templateContent = document.getElementById("txtRemark");
var content = "test";
insertText(templateContent, content);