HTMLInputElement: selectionStart 屬性

Baseline 已廣泛支援

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

HTMLInputElement 介面的 selectionStart 屬性是一個數字,表示所選文字的起始索引。當沒有選擇任何文字時,則返回 <input> 元素內文字輸入游標(caret)的位置。

注意:根據 WHATWG 表單規範selectionStart 屬性僅適用於 text、search、URL、tel 和 password 型別的 input。在現代瀏覽器中,在其他型別的 input 上設定 selectionStart 屬性會丟擲異常。此外,在非文字 input 元素上訪問 selectionStart 屬性時,此屬性返回 null

如果 selectionStart 大於 selectionEnd,則兩者都被視為 selectionEnd 的值。

一個非負整數。

示例

HTML

html
<!-- use selectionStart on non text input element -->
<label for="color">selectionStart property on type=color</label>
<input id="color" type="color" />

<!-- use selectionStart on text input element -->
<fieldset>
  <legend>selectionStart property on type=text</legend>
  <label for="statement">Select 'mdn' word from the text : </label>
  <input
    type="text"
    id="statement"
    value="The mdn is a documentation repository." />
  <button id="statement-btn">Select mdn text</button>
</fieldset>

JavaScript

js
const inputElement = document.getElementById("statement");
const statementBtn = document.getElementById("statement-btn");
const colorStart = document.getElementById("color");

statementBtn.addEventListener("click", () => {
  inputElement.selectionStart = 4;
  inputElement.selectionEnd = 7;
  inputElement.focus();
});

// open browser console to verify output
console.log(colorStart.selectionStart); // Output : null

結果

規範

規範
HTML
# dom-textarea/input-selectionstart

瀏覽器相容性

另見