欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

基于jQuery實(shí)現(xiàn)的設(shè)置文本區(qū)域的光標(biāo)位置

 更新時(shí)間:2018年06月15日 16:32:14   投稿:mdxy-dxy  
之前做一個(gè)代碼提示的功能涉及到在文本框中插入文本的操作,需要獲得當(dāng)前光標(biāo)位置插入文本,本文章向大家介紹jQuery如何設(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)在,您可以通過調(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個(gè)字符:$(elem).iDel(n);

這篇文章就介紹到這了,希望大家以后多多支持腳本之家。

相關(guān)文章

最新評論