遇到一个问题:表单输入框设置了文字,然后使用jQuery的焦点停留设置办法focus()进行处理。结果发现光标位置在firefox下停留的位置不对——停留在文字的最前边!
只有IE浏览器下是正常的。这样的话肯定是不行的,于是想办法进行处理。
代码有很多种,下面给出:
方法一:
- functionsetSelectionRange(input,selectionStart,selectionEnd){
- if(input.setSelectionRange){
- input.focus();
- input.setSelectionRange(selectionStart,selectionEnd);
- }
- elseif(input.createTextRange){
- varrange=input.createTextRange();
- range.collapse(true);
- range.moveEnd('character',selectionEnd);
- range.moveStart('character',selectionStart);
- range.select();
- }
- }
- functionsetCaretToPos(input,pos){
- setSelectionRange(input,pos,pos);
- }
调用办法:setCaretToPos(document.getElementById("YOURINPUT"), 4);
方法二:
- $.fn.selectRange=function(start,end){
- returnthis.each(function(){
- if(this.setSelectionRange){
- this.focus();
- this.setSelectionRange(start,end);
- }elseif(this.createTextRange){
- varrange=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)returnthis;
- return$(this).setSelection(position,position);
- }
- $.fn.setSelection=function(selectionStart,selectionEnd){
- if(this.lengh==0)returnthis;
- input=this[0];
- if(input.createTextRange){
- varrange=input.createTextRange();
- range.collapse(true);
- range.moveEnd('character',selectionEnd);
- range.moveStart('character',selectionStart);
- range.select();
- }elseif(input.setSelectionRange){
- input.focus();
- input.setSelectionRange(selectionStart,selectionEnd);
- }
- returnthis;
- }
- $.fn.focusEnd=function(){
- this.setCursorPosition(this.val().length);
- }
调用办法:$(element).focusEnd();