各浏览器TextArea获得焦点后的光标位置情况:
textarea.focus()
FireFox: 所有文字结束处
IE: 文字开头
Opera: 文字开头
Chrome: 文字开头
Safari: 文字开头
IE支持document.selection,Firefox,Chrome,Safari以及Opera都有selectionStart和selectionEnd属性。
针对浏览器的特性进行判断并实现,代码如下:
function 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; } else { obj.value += str; } } function moveEnd(obj){ obj.focus(); var len = obj.value.length; if (document.selection) { var sel = obj.createTextRange(); sel.moveStart('character',len); sel.collapse(); sel.select(); } else if (typeof obj.selectionStart == 'number' && typeof obj.selectionEnd == 'number') { obj.selectionStart = obj.selectionEnd = len; } }
参考:
http://foxling.org/js-ajax-dom/cross-browser-cursor-position-in-textarea/