Basic Svelte
Bindings
Classes and styles
Advanced Svelte
Advanced reactivity
Motion
Advanced bindings
Advanced transitions
Context API
Special elements
<script module>
Next steps
Basic SvelteKit
Introduction
Routing
Loading data
Headers and cookies
Shared modules
API routes
$app/state
Errors and redirects
Advanced SvelteKit
Page options
Link options
Advanced routing
Advanced loading
Environment variables
Conclusion
<svelte:document> 要素では document で発生するイベントをリスンすることができます。これは、selectionchange のような、window では発生しないイベントを扱うときに便利です。
onselectionchange ハンドラを <svelte:document> タグに追加します:
App
<svelte:document {onselectionchange} />
mouseenterやmouseleaveはすべてのブラウザでdocumentでは発生しないため、これらのハンドラをこの要素に追加しないでください。代わりに<svelte:body>を使用してください。
previous next
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>