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


当前回答

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

看看这个例子:

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

来源:CSS Tricks, MDN

其他回答

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

这个会有用的,试试这个

<input id="textField1" onfocus="this.select()" onmouseup="return false" /> 

可以在Safari/IE 9和Chrome上运行,但我没有机会在Firefox上测试。

这对我来说很管用(因为它不是在回答中,而是在评论中)

 $("#textBox").focus().select();

我的解决方案是:

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