Skip to main content
基本 Svelte
介绍
反应性
属性
逻辑
事件
绑定
类和样式
动作
转换
高级 Svelte
高级反应性
重用内容
运动
高级绑定
高级转换
上下文 API
特殊元素
<script module>
后续步骤
基本 SvelteKit
介绍
路由
加载数据
标题和 cookie
共享模块
表单
API 路由
$app/state
错误和重定向
高级 SvelteKit
钩子
页面选项
链接选项
高级路由
高级加载
环境变量
结论

<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} />

避免在此元素上使用 mouseentermouseleave 处理程序,因为这些事件不会在所有浏览器中的 document 上触发。改用 <svelte:body>

¥[!NOTE] Avoid mouseenter and mouseleave handlers on this element, as these events are not fired on document in all browsers. Use <svelte:body> instead.

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>