什么是香草JS或jQuery解决方案,将选择一个文本框的所有内容时,文本框接收焦点?


当前回答

这里的答案在某种程度上帮助了我,但当我在Chrome中单击向上/向下按钮时,我在HTML5数字输入字段上遇到了一个问题。

如果你点击其中一个按钮,并将鼠标放在按钮上,这个数字就会不断变化,就像你一直按住鼠标按钮一样,因为鼠标被扔掉了。

我通过删除mouseup处理程序来解决这个问题,一旦它被触发,如下所示:

    $("input:number").focus(function () {
        var $elem = $(this);
        $elem.select().mouseup(function (e) {
            e.preventDefault();
            $elem.unbind(e.type);
        });
    });

希望这能在未来帮助到人们…

其他回答

$(document).ready(function() {
    $("input:text")
        .focus(function () { $(this).select(); } )
        .mouseup(function (e) {e.preventDefault(); });
});

我的解决办法是使用暂停。看起来还行

$('input[type=text]').focus(function() {
    var _this = this;
    setTimeout(function() {
        _this.select();
    }, 10);
});
onclick="this.focus();this.select()"
$('input').focus(function () {
    var self = $(this);
    setTimeout(function () {
        self.select();
    }, 1);        
});

编辑:根据@DavidG的请求,我不能提供详细信息,因为我不确定为什么这样工作,但我相信这与向上或向下传播的焦点事件或任何它所做的事情有关,输入元素获得它所接收的焦点通知。设置timeout会给元素一点时间来意识到它已经这样做了。

jQuery不是JavaScript,在某些情况下JavaScript更容易使用。

看看这个例子:

<textarea rows="10" cols="50" onclick="this.focus();this.select()">Text is here</textarea>

来源:CSS Tricks, MDN