1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | //ie下 textarea失去焦点前要保存rang对象 var rie; //全局变量 function GetCursor() { if (document.all) {//IE要保存Range var obj = document.getElementById('content'); obj.focus(); rie = document.selection.createRange(); } } GetCursor(); function insertText(str,contentId) { var obj = document.getElementById(contentId); if (document.selection) { //ie obj.focus();//先激活当前对象 rie.text = str; } else if (typeof obj.selectionStart === 'number' && typeof obj.selectionEnd === 'number') { //非ie 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; } else { obj.value += str; } } insertText(哈哈,"J-content"); |
未经允许不得转载:开心乐窝-乐在其中 » JS指定光标位置插入内容