如何访问反应变量中div的offsetTop属性?
我有以下(简化的)结构:
DIV 1 (changing height because of an accordion)
–––--
DIV 2 (getting pushed down, offsetTop changing accordingly)
我想将 offsetTop 分配给 Svelte 中的反应变量,以便能够根据 DIV 2 的当前 offsetTop 进行计算。
我尝试过的:
<script>
let mapContainer;
$: map_offset = mapContainer?.offsetTop;
</script>
<div id="div1">
<!-- more going on here -->
</div>
<div id="div2" bind:this={mapContainer}>
{map_offset}
</div>
我使用可选链接来防止以下错误:
类型错误:无法读取未定义的属性(读取“offsetTop”)
我不再收到错误,并且在页面加载时使用值填充 map_offset,但当 DIV 1 更改其高度时,它不会更改,尽管我已经检查过 mapContainer.offsetTop已经改变了。我能做些什么?
I have the following (simplified) structure:
DIV 1 (changing height because of an accordion)
–––--
DIV 2 (getting pushed down, offsetTop changing accordingly)
I want to assign offsetTop to a reactive variable in Svelte to be able to do calculations based on the current offsetTop of DIV 2.
What I have tried:
<script>
let mapContainer;
$: map_offset = mapContainer?.offsetTop;
</script>
<div id="div1">
<!-- more going on here -->
</div>
<div id="div2" bind:this={mapContainer}>
{map_offset}
</div>
I used optional chaining to prevent the following error:
TypeError: Cannot read properties of undefined (reading 'offsetTop')
I am not getting errors anymore and map_offset is populated with a value when the page loads, but it does not change when DIV 1 changes its height although I have checked that mapContainer.offsetTop has changed. What can I do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的代码看起来非常好,并且在我看来应该可以工作。我会以同样的方式编写它,但我无法理解为什么反应式语句不运行。
希望其他人能给出一个解释。
与此同时,我所能提供的只是使用
afterUpdate
的解决方法,这是一个 Svelte 生命周期函数,每次更新组件时都会调用该函数:REPL 示例
Your code looks perfectly fine and should work in my opinion. I would have written it the same way, and I cannot understand why the reactive statement does not run.
Hopefully someone else will come up with an explanation.
In the meantime, all I can offer is a workaround using
afterUpdate
which is a Svelte lifecycle function that gets called everytime the component is updated:REPL example