这个方法setCursorPosition需要使用两个原生API
setSelectionRange
createTextRange
<html> <head> <title></title> <script src="./js/jquery-2.2.2.min.js"></script> </head> <body> <input type="text" id="test" /> <script> (function($, undefined) { $.fn.getCursorPosition = function() { var el = $(this).get(0); var pos = 0; if ('selectionStart' in el) { pos = el.selectionStart; } else if ('selection' in document) { el.focus(); var Sel = document.selection.createRange(); var SelLength = document.selection.createRange().text.length; Sel.moveStart('character', -el.value.length); pos = Sel.text.length - SelLength; } return pos; }; $.fn.setCursorPosition = function(option) { var settings = $.extend({ index: 0 }, option); return this.each(function() { var elem = this; var val = elem.value; var len = val.length; var index = settings.index; // 非input和textarea直接返回 var $elem = $(elem); if (!$elem.is('input,textarea')) { return; } // 超过文本长度直接返回 if (len < index) { return; } setTimeout(function() { elem.focus() if (elem.setSelectionRange) { // 标准浏览器 elem.setSelectionRange(index, index) ; } else { // IE9- var range = elem.createTextRange(); range.moveStart("character", -len); range.moveEnd("character", -len); range.moveStart("character", index); range.moveEnd("character", 0); range.select(); } }, 10); }); }; })(jQuery); $("#test").on("focus", function(){ var pos = $(this).getCursorPosition(); $(this).setCursorPosition({index:$(this).val().length}); }); </script> </body> </html>
Source:
http://www.uncletoo.com/html/jsjquery/755.html
http://www.cnblogs.com/snandy/p/4112488.html