我使用这段代码尝试在用户聚焦于字段时选择字段中的所有文本。发生的事情是,它选择了所有的一秒钟,然后它被取消选择,输入光标留在我点击的地方…

$("input[type=text]").focus(function() {
   $(this).select();
});

我希望一切都能被选中。


当前回答

与原生JavaScript select()一起工作很好。

$("input[type=text]").focus(function(event) {
   event.currentTarget.select();
});

或者概括地说:

$("input[type=text]")[0].select()

其他回答

我认为情况是这样的:

focus()
   UI tasks related to pre-focus
   callbacks
       select()
   UI tasks related to focus (which unselect again)

一个变通方法可能是异步调用select(),这样它就可以在focus()之后完全运行:

$("input[type=text]").focus(function() { 
    var save_this = $(this);
    window.setTimeout (function(){ 
       save_this.select(); 
    },100);
});
<script>$.ready( $("input[type=text]").attr("onclick" , "this.select()"));<script>

试着用点击代替聚焦。它似乎对鼠标和键事件都有效(至少在Chrome/Mac上):

jQuery < 1.7版本:

$("input[type='text']").click(function () {
   $(this).select();
});

jQuery 1.7+版本:

$("input[type='text']").on("click", function () {
   $(this).select();
});

这是一个演示

这个版本适用于ios,也修复了windows chrome上的标准拖拽选择

var srcEvent = null;

$("input[type=text],input[type=number]")

    .mousedown(function (event) {
        srcEvent = event;
    })

    .mouseup(function (event) {
        var delta = Math.abs(event.clientX - srcEvent.clientX) 
                  + Math.abs(event.clientY - srcEvent.clientY);

        var threshold = 2;
        if (delta <= threshold) {
                   try {
                        // ios likes this but windows-chrome does not on number fields
                        $(this)[0].selectionStart = 0;
                        $(this)[0].selectionEnd = 1000;
                    } catch (e) {
                        // windows-chrome likes this
                        $(this).select();
                    }
        }
    });

http://jsfiddle.net/Zx2sc/2/

这将完成工作,并避免您无法再通过鼠标选择部分文本的问题。

$("input[type=text]").click(function() {
    if(!$(this).hasClass("selected")) {
        $(this).select();
        $(this).addClass("selected");
    }
});
$("input[type=text]").blur(function() {
    if($(this).hasClass("selected")) {
        $(this).removeClass("selected");
    }
});