HTMLInputElement: selectionchange 事件

Baseline 2024
新推出

自 2024 年 9 月起,此功能已可在最新裝置和瀏覽器版本上使用。此功能可能無法在舊裝置或瀏覽器上使用。

selectionchange 事件是 Selection API 的一部分,當 <input> 元素中的文字選區發生改變時,會觸發該事件。這包括字元選區範圍的變化,或者游標的移動。

此事件不可取消。

通常,我們會透過在 <input> 元素上新增事件監聽器來處理此事件,並在處理函式中讀取 HTMLInputElementselectionStartselectionEndselectionDirection 屬性。

也可以向 onselectionchange 事件處理程式新增監聽器,並在處理函式中使用 Document.getSelection() 來獲取 Selection 物件。但是,這對於獲取文字選區變化來說用處不大。

語法

在諸如 addEventListener() 之類的方法中使用事件名稱,或設定事件處理程式屬性。

js
addEventListener("selectionchange", (event) => { })

onselectionchange = (event) => { }

事件型別

一個通用的 Event

示例

下面的示例展示瞭如何獲取 <input> 元素中選取的文字。

HTML

html
<div>
  Enter and select text here:<br /><input id="my-text" rows="2" cols="20" />
</div>
<div>selectionStart: <span id="start"></span></div>
<div>selectionEnd: <span id="end"></span></div>
<div>selectionDirection: <span id="direction"></span></div>

JavaScript

js
const myInput = document.getElementById("my-text");

myInput.addEventListener("selectionchange", () => {
  document.getElementById("start").textContent = myInput.selectionStart;
  document.getElementById("end").textContent = myInput.selectionEnd;
  document.getElementById("direction").textContent = myInput.selectionDirection;
});

結果

規範

規範
Selection API
# selectionchange-event
Selection API
# dom-globaleventhandlers-onselectionchange

瀏覽器相容性