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

瀏覽器相容性

另見