遇到一个问题:表单输入框设置了文字,而后使用jQuery的焦点停留设置办法focus()进行处理。结果发现光标位置在firefox下停留的位置不对——停留在文字的最前边!javascript
只有IE浏览器下是正常的。这样的话确定是不行的,因而想办法进行处理。java
代码有不少种,下面给出:浏览器
方法一:this
[javascript] view plaincopyspa
function setSelectionRange(input, selectionStart, selectionEnd) { .net
if (input.setSelectionRange) { firefox
input.focus(); code
input.setSelectionRange(selectionStart, selectionEnd); orm
} blog
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);
方法二:
[javascript] view plaincopy
$.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);
方法三:
[javascript] view plaincopy
$.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();