代码之家  ›  专栏  ›  技术社区  ›  SuperSIlly2

Svelte/TS通过foreach循环应用样式不会修改样式

  •  0
  • SuperSIlly2  · 技术社区  · 1 年前

    我一直试图在我的网站上创造一个很酷的“泡泡”效果,但我无法在前臂循环中改变造型。

    控制台中没有错误,所以我不确定应该做什么来调试它。
    这是代码:

    <script lang="ts">
        let bubbles:HTMLDivElement[]=[];
        let loaded:number=0;
        const ballAmount:number=15;
        function moveBubbles():void {
            bubbles.forEach((element)=>{
                element.style.top=Math.round((Math.random())*100)+"vh;";
                element.style.left=Math.round((Math.random())*100)+"vw;";
            });
            setTimeout(moveBubbles,15000);
        }
        moveBubbles();
    </script>
    
    <div class="bubbles">
        <div class="circles">
            {#each {length: ballAmount} as _, i}
                <div bind:this={bubbles[i]}
                    class="bubble"
                    style="
                        width: {Math.random()*25}vw;
                        opacity: {Math.random()*0.1};
                        top:{Math.random()*90}vh;
                        left:{Math.random()*100}vw;
                    "></div>
            {/each}
        </div>
        <div class="main">
            <slot></slot>
        </div>
    </div>
    
    <style>
        .bubble {
            transition: top left 15s linear;
            aspect-ratio: 1;
            position: absolute;
            background-color: var(--primary);
            border-radius: 100%;
            opacity: 0.02;
            z-index: 0;
        }
        .bubbles {
            width: 100vw;
            height: 100vh;
        }
        .main * {
            z-index: 5;
        }
    </style>
    

    我试过使用 on:load ,但我无法让它运行函数,与相同 use:moveBubbles .

    1 回复  |  直到 1 年前
        1
  •  2
  •   brunnerh    1 年前

    分配的值是无效的,因此由于流氓而被忽略 ; 单元之后:

    Math.round((Math.random())*100)+"vh;";
    

    请注意,您正在修改 style 其在模板中也具有插值。如果这些值是动态的,则脚本中的更改可能会被覆盖。

    通常,不建议直接操作DOM。 相反,我会存储一个数组 { x, y } 对象,并在模板中插入这些对象。在脚本中,您只需更改 数据 .

    <script lang="ts">
      const ballAmount = 15;
      let bubbles = randomLocations();
      setInterval(() => bubbles = randomLocations(), 1000);
    
      function randomLocations() {
        return Array.from({ length: ballAmount }, () => ({
          x: Math.round(Math.random() * 100) + "vw",
          y: Math.round(Math.random() * 100) + "vh",
        }));
      }
    </script>
    
    <div class="circles">
      {#each bubbles as { x, y }}
        <div class="bubble"
            style="
              width: {Math.random() * 25}vw;
              opacity: {Math.random() * 0.1};
              top: {y};
              left: {x};
            "></div>
      {/each}
    </div>
    

    (通常应在卸载/销毁组件时清理超时和间隔,以避免泄漏。为简洁起见,在代码示例中跳过了这一点。)

    REPL

    推荐文章