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


当前回答

这也适用于iOS:

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

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

其他回答

$(document).ready(function() {
    $("input:text").focus(function() { $(this).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;
     });
});

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

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

看看这个例子:

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

来源:CSS Tricks, MDN

HTML:

var textFiled = document.getElementById("text-filed"); 文本文件。addEventListener("focus", function() {this.select();}); 输入你的文本:<input type=" Text " id=" Text -filed" value="test with filed Text ">

使用JQuery:

$("#text-filed").focus(function() { $(this).select(); } );

使用React JS:

在各自的组成部分-

<input
  type="text"
  value="test"
  onFocus={e => e.target.select()}
/>

注意:如果你在ASP中编程。NET中,您可以使用ScriptManager运行脚本。c#中的RegisterStartupScript:

ScriptManager.RegisterStartupScript(txtField, txtField.GetType(), txtField.AccessKey, "$('#MainContent_txtField').focus(function() { $(this).select(); });", true );

或者在其他答案中建议的HTML页面中输入脚本。