基于jQuery實(shí)現(xiàn)的設(shè)置文本區(qū)域的光標(biāo)位置
如何使用jQuery在文本框中設(shè)置光標(biāo)位置?我有一個(gè)帶有內(nèi)容的文本字段,并且我希望光標(biāo)在焦點(diǎn)位于特定的偏移位置,該如何實(shí)現(xiàn)呢?
實(shí)現(xiàn)方法一:
這是一個(gè)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();
}
});
};
有了這個(gè),你可以做
$('#elem').selectRange(3,5); // select a range of text
$('#elem').selectRange(3); // set cursor position
實(shí)現(xiàn)方法二:
$.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;
}
現(xiàn)在,您可以通過(guò)調(diào)用以下任何元素將焦點(diǎn)移至任何元素的結(jié)尾
$(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);
}
調(diào)用辦法:
setCaretToPos(document.getElementById("YOURINPUT"), 4);
jquery中文本域光標(biāo)操作(選中、添加、刪除、獲取)
1、獲取光標(biāo)位置:$(elem).iGetFieldPos();
2、設(shè)置光標(biāo)位置:$(elem).iSelectField(start);
3、選中指定位置內(nèi)的字符:$(elem).iSelectField(start,end);
4、選中指定的字符:$(elem).iSelectStr(str);
5、在光標(biāo)之后插入字符串:$(elem).iAdd(str);
6、刪除光標(biāo)前面(-n)或者后面(n)的n個(gè)字符:$(elem).iDel(n);
這篇文章就介紹到這了,希望大家以后多多支持腳本之家。
相關(guān)文章
jQuery 2.0.3 源碼分析之core(一)整體架構(gòu)
這篇文章主要介紹了jQuery 2.0.3 源碼分析之core(一)整體架構(gòu),需要的朋友可以參考下2014-05-05
實(shí)例詳解jQuery表單驗(yàn)證插件validate
validate插件是一個(gè)基于jquery的表單驗(yàn)證插件了里面有許多的常用的一些驗(yàn)證方法我們可以直接調(diào)用,具體的我們一起來(lái)看看2016-01-01
jQuery1.3.2 升級(jí)到j(luò)Query1.4.4需要修改的地方
jQuery1.3.2 升級(jí)到 1.4.4 ,需要修改的地方,需要的朋友可以參考下。2011-01-01
鼠標(biāo)懸浮顯示二級(jí)菜單效果的jquery實(shí)現(xiàn)
當(dāng)鼠標(biāo)懸浮時(shí)顯示二級(jí)菜單,這種類似的效果,想必大家在瀏覽網(wǎng)頁(yè)時(shí)經(jīng)常會(huì)遇到吧,下面有個(gè)示例,大家可以看看2014-10-10

