--- title: HTMLInputElement.select() slug: Web/API/HTMLInputElement/select translation_of: Web/API/HTMLInputElement/select ---
HTMLInputElement.select()
方法选中一个 {{HTMLElement("textarea")}} 元素或者一个带有 text 字段的 {{HTMLElement("input")}} 元素里的所有内容。
element.select()
点击这个例子的按钮以选中所有在<input>
元素中的文字
HTML
<input type="text" id="text-box" size="20" value="Hello world!">
<button onclick="selectText()">Select text</button>
JavaScript
function selectText() {
const input = document.getElementById('text-box');
input.focus();
input.select();
}
{{EmbedLiveSample("示例")}}
调用 element.select()
并不一定会使得该 input 元素被 focused,所以它经常和 {{domxref("HTMLElement.focus()")}} 一起使用。
规范 | 状态 | 注释 |
---|---|---|
{{SpecName('HTML WHATWG', 'forms.html#dom-textarea/input-select', 'select')}} | {{Spec2('HTML WHATWG')}} |
{{Compat("api.HTMLInputElement.select")}}