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

$("input[type=text]").focus(function() {
   $(this).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);
        });
    }
});

其他回答

大多数这些解决方案的问题是,当在输入字段中更改光标位置时,它们不能正常工作。

onmouseup事件改变了字段中的光标位置,这是在onfocus之后触发的(至少在Chrome和FF中)。如果你无条件地丢弃鼠标,那么用户就不能用鼠标改变光标的位置。

function selectOnFocus(input) {
    input.each(function (index, elem) {
        var jelem = $(elem);
        var ignoreNextMouseUp = false;

        jelem.mousedown(function () {
            if (document.activeElement !== elem) {
                ignoreNextMouseUp = true;
            }
        });
        jelem.mouseup(function (ev) {
            if (ignoreNextMouseUp) {
                ev.preventDefault();
                ignoreNextMouseUp = false;
            }
        });
        jelem.focus(function () {
            jelem.select();
        });
    });
}
selectOnFocus($("#myInputElement"));

如果字段当前没有焦点,代码将有条件地阻止鼠标的默认行为。它适用于以下情况:

当字段未聚焦时单击 当域有焦点时单击 踏着踏着进入田野

我已经在Chrome 31、FF 26和IE 11中进行了测试。

这个版本适用于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/

var timeOutSelect;
$("input[type=text]").focus(function() { 
        var save_this = $(this);
        clearTimeout(timeOutSelect);
        timeOutSelect = window.setTimeout (function(){ 
                save_this.select(); 
        }, 100);
});

如果您在两个输入之间快速切换,请使用clearTimeout来获得更多的安全性。 清除旧的超时…

我认为情况是这样的:

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);
});

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

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

或者概括地说:

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