1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
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(); } |
使用方法:
1 2 3 |
var templateContent = document.getElementById("txtRemark"); var content = "test"; insertText(templateContent, content); |