jQuery文本框聚焦光标放在最后或想要的位置

11-20 | 夜光 | IT记录

如果直接给文本框设置focus(),那么对于不同的浏览器,光标聚焦的位置可能在最前面也可能在最后面。下面的代码是给jQuery扩展一个textFocus方法,用于使文本框聚焦在想要的位置:

	/**
	* 光标放在最后 $("#文本框ID").textFocus();
	* 光标放在第二个字符后面 $("#文本框ID").textFocus(2);
	*/
	(function($){
		$.fn.textFocus=function(v){
			var range,len,v=v===undefined?0:parseInt(v);
			this.each(function(){
				if($.browser.msie){
					range=this.createTextRange();
					v===0?range.collapse(false):range.move("character",v);
					range.select();
				}else{
					len=this.value.length;
					v===0?this.setSelectionRange(len,len):this.setSelectionRange(v,v);
				}
				this.focus();
			});
			return this;
		}
	})(jQuery)
本文标签:
本文链接: jquery-focus-the-cursor-at-the-end-of-the-text-box-or-desired-location/
版权所有: 玻璃泉, 转载请注明本文出处。