<svelte:window>
<svelte:window onevent={handler} />
<svelte:window bind:prop={value} />
<svelte:window>
元素允许你向 window
对象添加事件监听器,而不必担心在组件被销毁时删除它们,或者在服务器端渲染时检查 window
是否存在。
¥The <svelte:window>
element allows you to add event listeners to the window
object without worrying about removing them when the component is destroyed, or checking for the existence of window
when server-side rendering.
此元素只能出现在组件的顶层 - 它不能位于块或元素内。
¥This element may only appear at the top level of your component — it cannot be inside a block or element.
<script>
function handleKeydown(event) {
alert(`pressed the ${event.key} key`);
}
</script>
<svelte:window onkeydown={handleKeydown} />
你还可以绑定到以下属性:
¥You can also bind to the following properties:
innerWidth
innerHeight
outerWidth
outerHeight
scrollX
scrollY
online
—window.navigator.onLine
的别名¥
online
— an alias forwindow.navigator.onLine
devicePixelRatio
除 scrollX
和 scrollY
之外的所有文件都是只读的。
¥All except scrollX
and scrollY
are readonly.
<svelte:window bind:scrollY={y} />
请注意,页面不会滚动到初始值,以避免出现可访问性问题。只有对
scrollX
和scrollY
绑定变量的后续更改才会引起滚动。如果你有正当理由在组件渲染时滚动,请在$effect
中调用scrollTo()
。