Skip to main content

<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

  • onlinewindow.navigator.onLine 的别名

    ¥online — an alias for window.navigator.onLine

  • devicePixelRatio

scrollXscrollY 之外的所有文件都是只读的。

¥All except scrollX and scrollY are readonly.

<svelte:window bind:scrollY={y} />

请注意,页面不会滚动到初始值以避免可访问性问题。只有对 scrollXscrollY 的绑定变量的后续更改才会导致滚动。如果你有正当理由在渲染组件时滚动,请在 $effect 中调用 scrollTo()

¥[!NOTE] Note that the page will not be scrolled to the initial value to avoid accessibility issues. Only subsequent changes to the bound variable of scrollX and scrollY will cause scrolling. If you have a legitimate reason to scroll when the component is rendered, call scrollTo() in an $effect.