// 获取光标在文本框的位置 function _getFocus(elem) { var index = 0; if (document.selection) {// IE Support elem.focus(); var Sel = document.selection.createRange(); if (elem.nodeName === 'TEXTAREA') {//textarea var Sel2 = Sel.duplicate(); Sel2.moveToElementText(elem); var index = -1; while (Sel2.inRange(Sel)) { Sel2.moveStart('character'); index++; }; } else if (elem.nodeName === 'INPUT') {// input Sel.moveStart('character', -elem.value.length); index = Sel.text.length; } } else if (elem.selectionStart || elem.selectionStart == '0') { // Firefox support index = elem.selectionStart; } return (index); } //光标移动至末尾 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; } }
转载于:https://blog.51cto.com/smartwang/1357101