HTMLInputElement.select()

HTMLInputElement.select() 方法选中一个 <textarea> 元素或者一个带有 text 字段的 <input> 元素里的所有内容。

语法

element.select()

示例

点击这个例子的按钮以选中所有在<input>元素中的文字

HTML

html
<input type="text" id="text-box" size="20" value="Hello world!" />
<button onclick="selectText()">Select text</button>

JavaScript

js
function selectText() {
  const input = document.getElementById("text-box");
  input.focus();
  input.select();
}

结果

注意

调用 element.select() 并不一定会使得该 input 元素被 focused,所以它经常和 HTMLElement.focus() (en-US) 一起使用。

规范

Specification
HTML Standard
# dom-textarea/input-select

浏览器兼容性

BCD tables only load in the browser

相关链接