遇到一个问题:表单输入框设置了文字,然后使用jQuery的焦点停留设置办法focus()进行处理。结果发现光标位置在firefox下停留的位置不对——停留在文字的最前边!
只有IE浏览器下是正常的。这样的话肯定是不行的,于是想办法进行处理。终于找到了一些解决办法,效果如下
代码有很多种,下面给出:
方法一:
function setSelectionRange(input, selectionStart, selectionEnd) { if (input.setSelectionRange) { input.focus(); input.setSelectionRange(selectionStart, selectionEnd); } else if (input.createTextRange) { var range = input.createTextRange(); range.collapse(true); range.moveEnd('character', selectionEnd); range.moveStart('character', selectionStart); range.select(); } } function setCaretToPos (input, pos) { setSelectionRange(input, pos, pos); }
调用办法:setCaretToPos(document.getElementById("YOURINPUT"), 4);
方法二:
$.fn.selectRange = function(start, end) { return this.each(function() { if (this.setSelectionRange) { this.focus(); this.setSelectionRange(start, end); } else if (this.createTextRange) { var range = this.createTextRange(); range.collapse(true); range.moveEnd('character', end); range.moveStart('character', start); range.select(); } }); };
调用办法:$('#elem').selectRange(3,5);
方法三:
$.fn.setCursorPosition = function(position){ if(this.lengh == 0) return this; return $(this).setSelection(position, position); } $.fn.setSelection = function(selectionStart, selectionEnd) { if(this.lengh == 0) return this; input = this[0]; if (input.createTextRange) { var range = input.createTextRange(); range.collapse(true); range.moveEnd('character', selectionEnd); range.moveStart('character', selectionStart); range.select(); } else if (input.setSelectionRange) { input.focus(); input.setSelectionRange(selectionStart, selectionEnd); } return this; } $.fn.focusEnd = function(){ this.setCursorPosition(this.val().length); }
调用办法:$(element).focusEnd();
参与谈论:http://stackoverflow.com/questions/499126/jquery-set-cursor-position-in-text-area