Home  >  Article  >  php教程  >  jQuery点击input使光标移动到最后或指定位置

jQuery点击input使光标移动到最后或指定位置

WBOY
WBOYOriginal
2016-06-06 20:13:182468browse

你要知道面对一个 处女座的 需求者, focus()是远远不够的。 比如说“我点进去的时候光标要在最后,这样我就不用再把光标移动到最后去添加东西了。” oh,让我先撞下墙。 我们需要扩展jQuery: //光标放在最后 $("#文本框ID").textFocus();光标放在第二个字符

你要知道面对一个 处女座的 需求者, focus()是远远不够的。
比如说“我点进去的时候光标要在最后,这样我就不用再把光标移动到最后去添加东西了。”
oh,让我先撞下墙。
我们需要扩展jQuery:

//光标放在最后 $("#文本框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);

另一种简单的方法:
var t=$(“#”+id).val();
$(“#”+id).val(“”).focus().val(t);

建议采用第一种方法。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn