【问题标题】:Getting into a scrolling loop when shifting DomElements on scroll在滚动时移动 DomElements 时进入滚动循环
【发布时间】:2021-10-24 02:14:48
【问题描述】:

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

我已经能够使用 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 不起作用。

【问题讨论】:

    标签: javascript html dom svelte dom-manipulation


    【解决方案1】:

    在您的代码中设置 .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>
    

    【讨论】:

    • 我想这是正确的答案。但是这种行为在任何地方都有记录/描述吗?有什么办法阻止吗?如果我的项目确实需要像那样改变高度?
    【解决方案2】:

    删除.holder,改为使用position: fixedtop: 8px

    <script>
        let scroll;
    </script>
    
    <svelte:window bind:scrollY={scroll} />
    
    <div class="box" style="position:fixed;top:8px"></div>
    
    <style>
        :global(body) {
            height: 20000px;
        }
        .box {
            width: 200px;
            height: 200px;
            background-color: aqua;
        }
    </style>
    

    【讨论】:

    • 您好,您说的完全正确,这将解决蓝色框的问题。然而,这只是重现问题的最简单示例。当我添加所需的复杂性时,元素会以不同的方式更改,Dom 项目会在页面上的不同静态位置添加、移动和删除,因此将它们设置为固定是不够的。
    【解决方案3】:

    如果你需要增加高度,你可以按照下面的代码来做。

    <script>
        let scroll;
        $: height = Math.floor((scroll - 1)/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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      • 2018-03-14
      • 1970-01-01
      • 2021-01-08
      • 1970-01-01
      相关资源
      最近更新 更多