jQuery設置聚焦並使光標位置在文字最後

遇到一個問題:表單輸入框設置了文字,而後使用jQuery焦點停留設置辦法focus()進行處理。結果發現光標位置在firefox下停留的位置不對——停留在文字的最前邊!javascript

只有IE瀏覽器下是正常的。這樣的話確定是不行的,因而想辦法進行處理。java

代碼有不少種,下面給出:瀏覽器

方法一:this

[javascript] view plaincopyspa

  1. function setSelectionRange(input, selectionStart, selectionEnd) {  .net

  2.   if (input.setSelectionRange) {  firefox

  3.     input.focus();  code

  4.     input.setSelectionRange(selectionStart, selectionEnd);  orm

  5.   }  blog

  6.   else if (input.createTextRange) {  

  7.     var range = input.createTextRange();  

  8.     range.collapse(true);  

  9.     range.moveEnd('character', selectionEnd);  

  10.     range.moveStart('character', selectionStart);  

  11.     range.select();  

  12.   }  

  13. }  

  14.   

  15. function setCaretToPos (input, pos) {  

  16.   setSelectionRange(input, pos, pos);  

  17. }  


調用辦法:setCaretToPos(document.getElementById("YOURINPUT"), 4);

方法二:

[javascript] view plaincopy

  1. $.fn.selectRange = function(start, end) {  

  2.     return this.each(function() {  

  3.         if (this.setSelectionRange) {  

  4.             this.focus();  

  5.             this.setSelectionRange(start, end);  

  6.         } else if (this.createTextRange) {  

  7.             var range = this.createTextRange();  

  8.             range.collapse(true);  

  9.             range.moveEnd('character', end);  

  10.             range.moveStart('character', start);  

  11.             range.select();  

  12.         }  

  13.     });  

  14. };  


調用辦法:$('#elem').selectRange(3,5);

方法三:

[javascript] view plaincopy

  1. $.fn.setCursorPosition = function(position){  

  2.     if(this.lengh == 0) return this;  

  3.     return $(this).setSelection(position, position);  

  4. }  

  5.   

  6. $.fn.setSelection = function(selectionStart, selectionEnd) {  

  7.     if(this.lengh == 0) return this;  

  8.     input = this[0];  

  9.   

  10.     if (input.createTextRange) {  

  11.         var range = input.createTextRange();  

  12.         range.collapse(true);  

  13.         range.moveEnd('character', selectionEnd);  

  14.         range.moveStart('character', selectionStart);  

  15.         range.select();  

  16.     } else if (input.setSelectionRange) {  

  17.         input.focus();  

  18.         input.setSelectionRange(selectionStart, selectionEnd);  

  19.     }  

  20.   

  21.     return this;  

  22. }  

  23.   

  24. $.fn.focusEnd = function(){  

  25.     this.setCursorPosition(this.val().length);  

  26. }  


調用辦法:$(element).focusEnd();

相關文章
相關標籤/搜索