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 |
瀏覽器相容性
載入中…