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

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

我希望一切都能被选中。


当前回答

我来自2016年底,这段代码只适用于最新版本的jquery (jquery-2.1.3.js在这种情况下)。

if ($(element).is("input")) {
    $(element).focus(function () {
        $(element).select();
    });
}

其他回答

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

jQuery < 1.7版本:

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

jQuery 1.7+版本:

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

这是一个演示

你可以使用简单的代码:

$('#idname').select();

找到一个很棒的解决方案阅读这篇文章

$(function(){

    jQuery.selectText('input:text');
    jQuery.selectText('input:password');

});

jQuery.extend( {
    selectText: function(s) { 
        $(s).live('focus',function() {
            var self = $(this);
            setTimeout(function() {self.select();}, 0);
        });
    }
});

我总是使用requestAnimationFrame()来跳过内部事件后机制,这在Firefox中工作完美。还没有在Chrome上测试过。

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

我来自2016年底,这段代码只适用于最新版本的jquery (jquery-2.1.3.js在这种情况下)。

if ($(element).is("input")) {
    $(element).focus(function () {
        $(element).select();
    });
}