HTMLTextAreaElement: setSelectionRange() 方法
setSelectionRange()
方法是 HTMLTextAreaElement
接口的一个方法,用于设置 <textarea>
元素中当前文本选区的起始和结束位置,以及可选的选区方向。此方法会立即更新选区状态,但视觉上的高亮仅在元素获得焦点时才会出现。方向指示了选区被认为发生的方式;例如,用户通过从选中文本的末尾向开头拖动鼠标来设置选区。此外,还会触发 select
和 selectionchange
事件。
此方法会立即更新 HTMLTextAreaElement.selectionStart
、HTMLTextAreaElement.selectionEnd
和 HTMLTextAreaElement.selectionDirection
属性,无论元素是否获得焦点。视觉上的选区高亮需要元素获得焦点。
注意: 虽然 setSelectionRange()
会立即更新选区属性,但视觉上的选区高亮仅在 <textarea>
获得焦点时才会显示。聚焦该元素还会触发 selectionchange
事件。
要选择 <textarea>
元素的所有文本,请使用 HTMLTextAreaElement.select()
方法。
语法
setSelectionRange(selectionStart, selectionEnd)
setSelectionRange(selectionStart, selectionEnd, selectionDirection)
参数
selectionStart
-
第一个被选字符的索引。大于元素值长度的索引将被视为指向值的末尾。有关更多信息,请参阅
selectionStart
属性。 selectionEnd
-
最后一个被选字符之后的字符的索引。大于元素值长度的索引将被视为指向值的末尾。如果
selectionEnd
小于selectionStart
,则两者都被视为selectionEnd
的值。有关更多信息,请参阅selectionEnd
属性。 selectionDirection
可选-
关键字
"forward"
、"backward"
或默认值"none"
— 表示被认为已执行选区的方向。有关更多信息,请参阅selectionDirection
属性。
返回值
无(undefined
)。
示例
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 |
浏览器兼容性
加载中…