【发布时间】:2020-11-05 21:56:57
【问题描述】:
我正在尝试绑定到 Svelte 组件内 body 元素的总(滚动)高度,以便我可以在零和一之间的间隔内计算滚动位置。 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>
在这个例子中,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>
同样,在调整正文大小时不会调用handleResize 函数。
有没有办法在 Svelte 中惯用地解决这个问题?
在挂载时手动绑定到 body 的 resize 事件并从那里更新值是否安全?
感谢您抽出宝贵时间阅读此问题!
【问题讨论】:
标签: javascript svelte