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


当前回答

onclick="this.focus();this.select()"

其他回答

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

您只需要添加以下属性:

onfocus="this.select()"

例如:

<input type="text" value="sometext" onfocus="this.select()">

(说实话,我不知道你为什么还需要其他东西。)

这也适用于iOS:

<input type="text" onclick="this.focus(); this.setSelectionRange(0, 9999);" />

https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select

如果你把这些事件链接在一起,我相信就不需要使用.one了,就像本文其他地方建议的那样。

例子:

$('input.your_element').focus( function () {
    $(this).select().mouseup( function (e) {
        e.preventDefault();
    });
});

我的解决方案是:

var mouseUp;
$(document).ready(function() {
    $(inputSelector).focus(function() {
        this.select();
    }) 
    .mousedown(function () {
        if ($(this).is(":focus")) {
          mouseUp = true;
        }
        else {
          mouseUp = false;
        }
     })
     .mouseup(function () {
        return mouseUp;
     });
});

因此,鼠标通常会工作,但不会在通过输入获得焦点后取消选择

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

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