Skip to main content
Svelte基础
介绍
响应
属性Props
逻辑表达式
事件
绑定
Classes和样式
动作Actions
转场
Svelte高阶
响应式进阶
内容复用
动画
高级绑定
高级转场
上下文API
特殊元素
脚本模块
接下来
SvelteKit基础
介绍
路由
加载数据
Headers和cookies
Shared modules
Forms
API routes
$app/state
Errors and redirects
Advanced SvelteKit
Hooks
Page options
Link options
Advanced routing
Advanced loading
Environment variables
Conclusion

支持了window当然也不能忘了document不是,毕竟有些事件还非得在document上触发, 比如: selectionchange .
来使用<svelte:document>document对象添加上onselectionchange事件处理函数:

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. Add the onselectionchange handler to the <svelte:document> tag:

App
<svelte:document {onselectionchange} />

偷偷告诉尽量避免在document元素上使用mouseentermouseleave哦,因为有些浏览器不支持,可以用在<svelte:body>上. 这都是技巧

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

Edit this page on GitHub

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

loading Svelte compiler...
loading svelte compiler