方法一:调用办法:setCaretToPos(document.getElementById("YOURINPUT"), 4);
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);
}
方法二:调用办法:$('#elem').selectRange(3,5);
$.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();
}
});
};
方法三:调用办法:$(element).focusEnd();
$.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);
}