HTMLTextAreaElement: selectionchange event

Baseline 2024
Newly available

Since September 2024, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

Sự kiện selectionchange của Selection API được kích hoạt khi vùng chọn văn bản bên trong phần tử <textarea> thay đổi. Điều này bao gồm cả thay đổi trong phạm vi ký tự được chọn, hoặc khi con trỏ nhập di chuyển.

Sự kiện này không thể hủy.

Sự kiện thường được xử lý bằng cách thêm trình lắng nghe sự kiện lên <textarea>, và trong hàm xử lý đọc các thuộc tính selectionStart, selectionEndselectionDirection của HTMLTextAreaElement.

Cũng có thể thêm trình lắng nghe lên trình xử lý sự kiện toàn cục onselectionchange, và trong hàm xử lý dùng Document.getSelection() để lấy Selection. Tuy nhiên cách này không thật sự hữu ích để lấy thay đổi của vùng chọn văn bản.

Cú pháp

Dùng tên sự kiện trong các phương thức như addEventListener(), hoặc đặt thuộc tính trình xử lý sự kiện.

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

onselectionchange = (event) => { }

Loại sự kiện

Một Event chung.

Ví dụ

Ví dụ dưới đây cho thấy cách lấy văn bản được chọn trong phần tử <textarea>.

HTML

html
<div>
  Enter and select text here:<br /><textarea
    id="my-text"
    rows="2"
    cols="20"></textarea>
</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;
});

Kết quả

Đặc tả kỹ thuật

Specification
Selection API
# selectionchange-event
Selection API
# dom-globaleventhandlers-onselectionchange

Tương thích trình duyệt