首页 > 解决方案 > 在滚动时移动 DomElements 时进入滚动循环

问题描述

我正在构建一个虚拟网格,它将根据需要将内容放置到视口中,尤其是在用户滚动时。

我已经能够使用 React 实现这种行为,但我似乎在使用 svelte 时遇到了麻烦。

    <script>
    let scroll;
    $: height = Math.floor(scroll/200)*200;
</script>

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


<div class="holder" style="height:{height}px"></div>
<div class="box"></div>



<style>
    :global(body) {
        height: 20000px;
    }
    .box {
        width: 200px;
        height: 200px;
        background-color: aqua;
    }
    .holder {

    }
</style>

REPL

当我滚动时,底部 div 的高度增加以提升蓝色框,某些东西触发了进一步的滚动,然后触发了进一步的高度增加,从而触发了进一步的滚动。

所以基本上当你滚动一点时,滚动条会变得疯狂并在电脑上向下滑动。

理想情况下,页面应该从用户输入正常滚动。

不确定这是否是 svelte 的问题,或者这是否是某些默认浏览器行为。

编辑:更改代码和 repl 以更多地反映我的要求,这说明了为什么设置“位置:固定”css 不起作用。

标签: javascripthtmldomsveltedom-manipulation

解决方案


在您的代码中设置 .holder 的高度会改变滚动。所以它陷入连续循环直到触底。

<script>
    let scroll;
    $: top = Math.floor(scroll/200)*200;
</script>

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

<div class="box" style="top:{top}px"></div>

<style>
    :global(body) {
        height: 20000px;
    }
    .box {
        position: absolute;
        top: 0;
        width: 200px;
        height: 200px;
        background-color: aqua;
    }
</style>

推荐阅读