新聞中心
如何使用jQuery在文本框中設(shè)置光標(biāo)位置?我有一個帶有內(nèi)容的文本字段,并且我希望光標(biāo)在焦點(diǎn)位于特定的偏移位置,該如何實(shí)現(xiàn)呢?
成都創(chuàng)新互聯(lián),專注為中小企業(yè)提供官網(wǎng)建設(shè)、營銷型網(wǎng)站制作、響應(yīng)式網(wǎng)站開發(fā)、展示型成都網(wǎng)站設(shè)計(jì)、成都做網(wǎng)站等服務(wù),幫助中小企業(yè)通過網(wǎng)站體現(xiàn)價值、有效益。幫助企業(yè)快速建站、解決網(wǎng)站建設(shè)與網(wǎng)站營銷推廣問題。
實(shí)現(xiàn)方法一:
這是一個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
實(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)在,您可以通過調(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)操作(選中、添加、刪除、獲?。?/strong>
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個字符:$(elem).iDel(n);
這篇文章就介紹到這了,希望大家以后多多支持創(chuàng)新互聯(lián)。
當(dāng)前標(biāo)題:基于jQuery實(shí)現(xiàn)的設(shè)置文本區(qū)域的光標(biāo)位置
本文地址:http://fisionsoft.com.cn/article/isghho.html