遇到一个问题:表单输入框设置了文字,然后使用jQuery的焦点停留设置办法focus()进行处理。结果发现光标位置在firefox下停留的位置不对——停留在文字的最前边!
只有IE浏览器下是正常的。这样的话肯定是不行的,于是想办法进行处理。终于找到了一些解决办法,效果如下
代码有很多种,下面给出:
方法一:
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();
参与谈论:http://stackoverflow.com/questions/499126/jquery-set-cursor-position-in-text-area
本文介绍了一个在Firefox浏览器中使用jQuery解决表单输入框光标位置偏移的问题,并提供了三种不同的解决方法,包括方法一、方法二和方法三,以及它们的具体实现代码。通过这些方法,可以确保光标在输入框内正确定位,提高用户体验。
2206

被折叠的 条评论
为什么被折叠?



