You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现仅当坐标在指定范围时执行Element.animate动画

解决小球超出Header区域显示的问题

最简单的方案是利用CSS的overflow:hidden属性配合调整小球的父容器,不需要复杂的JS坐标判断:

具体修改步骤

  1. 给#header添加overflow:hidden样式,自动裁剪超出header范围的内容
  2. 将小球的挂载目标从document.body改为header容器,确保小球属于header的子元素,让裁剪规则生效

修改后的完整代码如下:

<!DOCTYPE html>
<html>
<head>
    <link href="https://fonts.cdnfonts.com/css/monaco" rel="stylesheet">
    <meta charset="utf-8" />
    <title>Test</title>
    <style>
        body {
            margin: 0;
            width: 100%;
        }

        #header {
            position: relative;
            height: 580px;
            width: 100%;
            margin: 0;
            padding: 0;
            overflow: hidden; /* 新增:裁剪超出内容 */
        }

        #about {
            position: relative;
            height: auto;
            background-color: #f9f9f9;
            width: 100%;
            margin: 0;
            padding: 0;
        }

        .subtitle {
            position: relative;
            top: 40px;
            left: 10%;
            font-family: Monaco;
            color: #1e9912;
            font-size: 30px;
            font-weight: 200;
            width: fit-content;
            margin-right: 0px;
        }

        .ball {
            position: absolute;
            border-radius: 100%;
            opacity: 0.7;
        }

        #bio {
            top: 10px;
            position: relative;
            left: 20%;
            width: 70%;
            font-family: Monaco;
            font-size: 20px;
            line-height: 1.6;
            padding-bottom: 30px;
            margin-right: 0px;
        }
    </style>

</head>

<body>
    <div id="header">
    </div>
    <div id="about">
        <h3 class="subtitle">About</h3>
        <div id="bio">
            <p>Long text.</p>
            <p>continue long text.</p>
        </div>
    </div>
    <script>
        // Some random colors
        const colors = ["#3CC157", "#2AA7FF", "#1B1B1B", "#FCBC0F", "#F85F36"];
        const numBalls = 100;


        let balls = [];

        function initializeBalls() {
            const header = document.getElementById("header"); // 提前获取header元素
            for (let i = 0; i < numBalls; i++) {
                let ball = document.createElement("div");
                ball.classList.add("ball");
                ball.style.background = colors[Math.floor(Math.random() * colors.length)];
                ball.style.left = `${Math.floor(Math.random() * header.offsetWidth)}px`;
                ball.style.top = `${Math.floor(Math.random() * header.offsetHeight)}px`;
                ball.style.transform = `scale(${Math.random()})`;
                ball.style.width = `${Math.random()}em`;
                ball.style.height = ball.style.width;

                balls.push(ball);
                header.append(ball); // 修改:将小球添加到header内,而非body
            }

            // Keyframes
            balls.forEach((el, i, ra) => {
                let to = {
                    x: Math.random() * (i % 2 === 0 ? -110 : 110),
                    y: Math.random() * 120
                };

                let anim = el.animate(
                    [
                        { transform: "translate(0, 0)" },
                        { transform: `translate(${to.x}px, ${to.y}px)` }
                    ],
                    {
                        duration: (Math.random() + 1) * 2000, // random duration
                        direction: "alternate",
                        fill: "both",
                        iterations: Infinity,
                        easing: "ease-in-out"
                    }
                );
            });
        }
        initializeBalls();
    </script>
</body>
</html>

原理说明

  • overflow:hidden是CSS中处理容器内容溢出的专用属性,子元素超出容器边界时,超出部分会被直接隐藏,完全匹配你需要的"小球移出指定范围不再显示"的效果
  • 将小球放在header容器内,既符合页面结构逻辑(动画属于header区域),又能让overflow:hidden的裁剪规则正确作用在小球上,实现零JS逻辑的边界隐藏效果

内容的提问来源于stack exchange,提问作者Benedict Schlüter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 13:30:54