此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in English Always switch to English

HTMLInputElement.select()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨2015年7月⁩.

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() 一起使用。

规范

Specification
HTML
# dom-textarea/input-select

浏览器兼容性

相关链接