【问题标题】:Bind to offsetHeight of the <body> from inside a Svelte component从 Svelte 组件内部绑定到 <body> 的 offsetHeight
【发布时间】:2020-11-05 21:56:57
【问题描述】:

我正在尝试绑定到 Svelte 组件内 body 元素的总(滚动)高度,以便我可以在零和一之间的间隔内计算滚动位置。 This allows for some cool scroll-triggered CSS animations. 我要查找的值存储在 body.offsetHeight 属性中。

我的第一个想法是直接使用&lt;svelte:body&gt; 元素绑定属性。

<script>
    let h;
</script>
<svelte:body bind:offsetHeight={h}></svelte:body>
<span class="debug">{h}</span>

在这个例子中,h 将保持未定义,即使窗口被调整大小。
The documentation mentions that the &lt;svelte:...&gt; 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


    【解决方案1】:

    您可以在窗口元素本身上设置on:resize

    <svelte:window on:resize={handleResize}></svelte:window>
    

    或者,您也可以从窗口中获取相同的信息?那里的绑定工作顺利。

    【讨论】:

    • 不幸的是,窗口没有为该信息公开任何绑定,但窗口上的事件有效,非常感谢!感觉有点不修边幅。。
    • 不,我猜在窗口上你会有outerHeightscrollY
    猜你喜欢
    • 2017-04-24
    • 2011-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多