从 Svelte 组件内部绑定到 <body> 的 offsetHeight
Bind to offsetHeight of the <body> from inside a Svelte component
我正在尝试绑定到 Svelte 组件内 body 元素的总(滚动)高度,以便我可以在 0 到 1 之间的间隔内计算滚动位置。 This allows for some cool scroll-triggered CSS animations. 我要查找的值存储在 body.offsetHeight
属性.
我的第一个想法是直接使用 <svelte:body>
元素绑定 属性。
<script>
let h;
</script>
<svelte:body bind:offsetHeight={h}></svelte:body>
<span class="debug">{h}</span>
在此示例中,即使 window 已调整大小,h
仍将保持未定义状态。
The documentation mentions that the <svelte:...>
elements are primariliy intended to bind event listeners to them. 考虑到这一点,我尝试绑定 resize
事件并从那里获取尺寸,以及 onMount
回调中 body.offsetHeight
的初始值。
<script>
const handleResize = () => { console.log("yay"); };
</script>
<svelte:body on:resize={handleResize}></svelte:body>
再次调整 body 大小时,handleResize
函数不会被调用。
有没有办法在 Svelte 中以惯用的方式解决这个问题?
在 on-mount 中手动绑定到 body 的 resize
事件并从那里更新值是否安全?
感谢您花时间阅读这个问题!
您可以在 window 元素本身上设置 on:resize
<svelte:window on:resize={handleResize}></svelte:window>
或者,您也可以从 window 获得相同的信息?绑定工作顺利。
我正在尝试绑定到 Svelte 组件内 body 元素的总(滚动)高度,以便我可以在 0 到 1 之间的间隔内计算滚动位置。 This allows for some cool scroll-triggered CSS animations. 我要查找的值存储在 body.offsetHeight
属性.
我的第一个想法是直接使用 <svelte:body>
元素绑定 属性。
<script>
let h;
</script>
<svelte:body bind:offsetHeight={h}></svelte:body>
<span class="debug">{h}</span>
在此示例中,即使 window 已调整大小,h
仍将保持未定义状态。
The documentation mentions that the <svelte:...>
elements are primariliy intended to bind event listeners to them. 考虑到这一点,我尝试绑定 resize
事件并从那里获取尺寸,以及 onMount
回调中 body.offsetHeight
的初始值。
<script>
const handleResize = () => { console.log("yay"); };
</script>
<svelte:body on:resize={handleResize}></svelte:body>
再次调整 body 大小时,handleResize
函数不会被调用。
有没有办法在 Svelte 中以惯用的方式解决这个问题?
在 on-mount 中手动绑定到 body 的 resize
事件并从那里更新值是否安全?
感谢您花时间阅读这个问题!
您可以在 window 元素本身上设置 on:resize
<svelte:window on:resize={handleResize}></svelte:window>
或者,您也可以从 window 获得相同的信息?绑定工作顺利。