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

浏览器兼容性

另见