<svelte:document> 元素允许你监听在 document 上触发的事件。这对于 selectionchange 之类的事件很有用,因为 window 不会触发。
¥The <svelte:document> element allows you to listen for events that fire on document. This is useful with events like selectionchange, which doesn’t fire on window.
将 onselectionchange 处理程序添加到 <svelte:document> 标签:
¥Add the onselectionchange handler to the <svelte:document> tag:
App
<svelte:document {onselectionchange} />避免在此元素上使用
mouseenter和mouseleave处理程序,因为这些事件并非在所有浏览器中的document上都会触发。改用<svelte:body>。
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>