Python语言技术文档

微信小程序技术文档

php语言技术文档

jsp语言技术文档

asp语言技术文档

C#/.NET语言技术文档

html5/css技术文档

javascript

点击排行

您现在的位置:首页 > 技术文档 > jquery

基于jQuery实现的设置文本区域的光标位置

来源:中文源码网    浏览:376 次    日期:2024-04-23 00:57:54
【下载文档:  基于jQuery实现的设置文本区域的光标位置.txt 】


基于jQuery实现的设置文本区域的光标位置
如何使用jQuery在文本框中设置光标位置?我有一个带有内容的文本字段,并且我希望光标在焦点位于特定的偏移位置,该如何实现呢?
实现方法一:
这是一个jQuery解决方案:
$.fn.selectRange = function(start, end) {
if(end === undefined) {
end = start;
}
return this.each(function() {
if('selectionStart' in this) {
this.selectionStart = start;
this.selectionEnd = end;
} else if(this.setSelectionRange) {
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); // select a range of text
$('#elem').selectRange(3); // set cursor position
实现方法二:
$.fn.setCursorPosition = function(position){
if(this.length == 0) return this;
return $(this).setSelection(position, position);
}
$.fn.setSelection = function(selectionStart, selectionEnd) {
if(this.length == 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);
return this;
}
现在,您可以通过调用以下任何元素将焦点移至任何元素的结尾
$(element).focusEnd();
方法三
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);
jquery中文本域光标操作(选中、添加、删除、获取)
1、获取光标位置:$(elem).iGetFieldPos();
2、设置光标位置:$(elem).iSelectField(start);
3、选中指定位置内的字符:$(elem).iSelectField(start,end);
4、选中指定的字符:$(elem).iSelectStr(str);
5、在光标之后插入字符串:$(elem).iAdd(str);
6、删除光标前面(-n)或者后面(n)的n个字符:$(elem).iDel(n);
这篇文章就介绍到这了,希望大家以后多多支持中文源码网。

相关内容