跳到主要內容

<svelte:document> 元素允許你監聽在 document 上觸發的事件。這對於像 selectionchange 這樣的事件很有用,因為它不會在 window 上觸發。

onselectionchange 處理器新增到 <svelte:document> 標籤

App
<svelte:document {onselectionchange} />

避免在此元素上使用 mouseentermouseleave 處理器,因為這些事件並非在所有瀏覽器的 document 上觸發。請改用 <svelte:body>

在 GitHub 上編輯此頁面

1
2
3
4
5
6
7
8
9
10
11
12
13
<script>
	let selection = $state('');
 
	const onselectionchange = (e) => {
		selection = document.getSelection().toString();
	};
</script>
 
<svelte:document />
 
<h1>Select this text to fire events</h1>
<p>Selection: {selection}</p>