HTMLInputElement: select() 方法

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

HTMLInputElement.select() 方法會選中一個 <textarea> 元素或包含文字欄位的 <input> 元素中的所有文字。

語法

js
select()

引數

無。

返回值

無(undefined)。

示例

在此示例中,單擊按鈕以選中 <input> 元素中的所有文字。

HTML

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

JavaScript

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

document.querySelector("button").addEventListener("click", selectText);

結果

注意

呼叫 element.select() 不一定會使輸入框獲得焦點,因此它經常與 HTMLElement.focus 一起使用。

規範

規範
HTML
# dom-textarea/input-select

瀏覽器相容性

另見