方法一:
- 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);
方法二:
- $.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);
方法三:
- $.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();
阻止某些文字被选中
$.fn.disableSelection
".ui-disableSelection", function( event ) {
event.preventDefault();
});
}