遇到一個問題:表單輸入框設置了文字,而後使用jQuery的焦點停留設置辦法focus()進行處理。結果發現光標位置在firefox下停留的位置不對——停留在文字的最前邊!javascript
只有IE瀏覽器下是正常的。這樣的話確定是不行的,因而想辦法進行處理。java
代碼有不少種,下面給出:jquery
方法一:瀏覽器
- 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);
this
方法二:spa
- $.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);
.net
方法三:firefox
- $.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();code