如何在页面加载时自动选择输入字段及其中的文本

der*_*ick 63 html javascript

在页面加载时,我想将光标移动到特定字段.没问题.但我还需要选择并突出显示该文本字段中的默认值.

Joh*_*kin 95

来自http://www.codeave.com/javascript/code.asp?u_log=7004:

var input = document.getElementById('myTextInput');
input.focus();
input.select();
Run Code Online (Sandbox Code Playgroud)
<input id="myTextInput" value="Hello world!" />
Run Code Online (Sandbox Code Playgroud)

  • 这适用于 Firefox,但不会选择 Chrome 或 Edge 中的文本。 (3认同)

小智 33

在输入标记中,放置以下内容:

onFocus="this.select()"
Run Code Online (Sandbox Code Playgroud)

  • 刚尝试过并在Chrome上运行(`版本55.0.2883.95(64位)`) (3认同)

Viv*_* ab 21

试试这个.这适用于Firefox和Chrome.

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


roe*_*ing 15

要在页面加载上执行此操作:

window.onload = function () {
  var input = document.getElementById('myTextInput');
  input.focus();
  input.select();
}
Run Code Online (Sandbox Code Playgroud)
<input id="myTextInput" value="Hello world!" />
Run Code Online (Sandbox Code Playgroud)


ped*_*off 5

我找到了一个非常简单的方法,效果很好:

<input type="text" onclick="this.focus();this.select()">
Run Code Online (Sandbox Code Playgroud)


小智 5

在您的输入标签中使用自动对焦,如下所示

<input type="text" autofocus>
Run Code Online (Sandbox Code Playgroud)