HTMLTextAreaElement: setSelectionRange() 方法

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

setSelectionRange() 方法是 HTMLTextAreaElement 接口的一个方法,用于设置 <textarea> 元素中当前文本选区的起始和结束位置,以及可选的选区方向。此方法会立即更新选区状态,但视觉上的高亮仅在元素获得焦点时才会出现。方向指示了选区被认为发生的方式;例如,用户通过从选中文本的末尾向开头拖动鼠标来设置选区。此外,还会触发 selectselectionchange 事件。

此方法会立即更新 HTMLTextAreaElement.selectionStartHTMLTextAreaElement.selectionEndHTMLTextAreaElement.selectionDirection 属性,无论元素是否获得焦点。视觉上的选区高亮需要元素获得焦点。

注意: 虽然 setSelectionRange() 会立即更新选区属性,但视觉上的选区高亮仅在 <textarea> 获得焦点时才会显示。聚焦该元素还会触发 selectionchange 事件。

要选择 <textarea> 元素的所有文本,请使用 HTMLTextAreaElement.select() 方法。

语法

js
setSelectionRange(selectionStart, selectionEnd)
setSelectionRange(selectionStart, selectionEnd, selectionDirection)

参数

selectionStart

第一个被选字符的索引。大于元素值长度的索引将被视为指向值的末尾。有关更多信息,请参阅 selectionStart 属性。

selectionEnd

最后一个被选字符之后的字符的索引。大于元素值长度的索引将被视为指向值的末尾。如果 selectionEnd 小于 selectionStart,则两者都被视为 selectionEnd 的值。有关更多信息,请参阅 selectionEnd 属性。

selectionDirection 可选

关键字 "forward""backward" 或默认值 "none" — 表示被认为已执行选区的方向。有关更多信息,请参阅 selectionDirection 属性。

返回值

无(undefined)。

示例

js
const textarea = document.getElementById("text-box");
const chars = textarea.textLength;
// if the value is more than 10 characters long
if (chars > 10) {
  // Element must be focused to select a range of text within it
  textarea.focus();
  // select the text between the fifth character from the start and
  // the fifth character from the end
  textarea.setSelectionRange(5, chars - 5);
} else {
  // otherwise select all the text
  textarea.select();
}

规范

规范
HTML
# dom-textarea/input-setselectionrange-dev

浏览器兼容性

另见