HTMLInputElement: selectionEnd 屬性

Baseline 已廣泛支援

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

HTMLInputElement 介面的 selectionEnd 屬性是一個數字,表示選定文字的結束索引。當沒有選中文字時,它返回緊跟在當前文字輸入游標位置之後的字元的偏移量。

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

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

一個非負整數。

示例

HTML

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

<!-- using selectionEnd on text input element -->
<fieldset>
  <legend>selectionEnd property on type=text</legend>
  <label for="pin">Input PIN</label>
  <input type="text" id="pin" value="impossible PIN: 102-12-145" />
  <button id="pin-btn" type="button">PIN correction</button>
</fieldset>

JavaScript

js
const colorEnd = document.getElementById("color");
const text = document.querySelector("#pin");
const pinBtn = document.querySelector("#pin-btn");
const validPinChecker = /^\d{3}-\d{2}-\d{3}/g;
const selectionEnd = text.value.length;
const selectedText = text.value.substring(text.selectionStart, selectionEnd);

pinBtn.addEventListener("click", () => {
  const correctedText = selectedText.replace(validPinChecker, "");
  text.value = correctedText;
});

// open browser console to verify output
console.log(colorEnd.selectionEnd); // Output : null

結果

規範

規範
HTML
# dom-textarea/input-selectionend

瀏覽器相容性

另見