HTMLInputElement: sự kiện selectionchange
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 lựa chọn văn bản trong phần tử <input> thay đổi.
Điều này bao gồm cả thay đổi trong phạm vi ký tự được chọn, hoặc nếu con trỏ 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 trên <input>, và trong hàm xử lý đọc các thuộc tính selectionStart, selectionEnd và selectionDirection của HTMLInputElement.
Cũng có thể thêm trình lắng nghe trên trình xử lý sự kiện onselectionchange, và trong hàm xử lý sử dụng Document.getSelection() để lấy Selection. Tuy nhiên, điều này không hữu ích lắm để nhận các thay đổi lựa chọn văn bản.
Cú pháp
Sử 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.
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ử <input>.
HTML
<div>
Nhập và chọn văn bản tại đây:<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
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
| Thông số kỹ thuật |
|---|
| Selection API> # selectionchange-event> |
| Selection API> # dom-globaleventhandlers-onselectionchange> |