Skip to main content

Phần tử <svelte:document> cho phép bạn lắng nghe các sự kiện xảy ra trên document. Điều này hữu ích với các sự kiện như selectionchange, không xảy ra trên window.

Thêm xử lý sự kiện selectionchange vào thẻ <svelte:document>:

App.svelte
<svelte:document on:selectionchange={handleSelectionChange} />

Tránh sử dụng các xử lý sự kiện mouseentermouseleave trên phần tử này, vì những sự kiện này không được kích hoạt trên document trên tất cả các trình duyệt. Thay vào đó hãy sử dụng svelte:body.

Tiếp theo: <svelte:head>

1
2
3
4
5
6
7
8
9
10
11
<script>
	let selection = '';
 
	const handleSelectionChange = (e) => selection = document.getSelection();
</script>
 
<svelte:document />
 
<h1>Chọn văn bản để kích hoạt sự kiện</h1>
<p>Lựa chọn: {selection}</p>
 
initialising