滚动的小球

Tutorial: DOM实战 Category: JS Published: 2026-04-07 13:58:26 Views: 20 Likes: 0 Comments: 0
<!DOCTYPE html>
<html lang="en">
  <head>
    <style>
      * {
        padding: 0;
        margin: 0;
      }

      body {
        overflow: hidden;
      }

      div {
        position: absolute;
        background-color: aqua;
        border-radius: 50%;
        cursor: pointer;
      }
    </style>
  </head>
  <body>
    <script>
      function genNum(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
      }

      window.addEventListener("load", function () {
        const HEIGHT = window.innerHeight;
        const WIDTH = window.innerWidth;
        const body = document.body;

        const ballList = [];
        for (i = 0; i < 20; i++) {
          const div = document.createElement("div");
          const xspeed = genNum(-4, 4);
          const yspeed = genNum(-4, 4);
          const RADIUS = genNum(20, 70);

          div.xspeed = xspeed;
          div.yspeed = yspeed;

          div.style.height = RADIUS + "px";
          div.style.width = RADIUS + "px";
          div.style.zIndex = i;
          div.style.backgroundColor =
            "#" + parseInt(Math.random() * 0xffffff).toString(16);

          div.addEventListener("mouseenter", function () {
            div.xspeed = 0;
            div.yspeed = 0;
            div.style.height = 100 + "px";
            div.style.width = 100 + "px";
          });

          div.addEventListener("mouseleave", function () {
            div.xspeed = xspeed;
            div.yspeed = yspeed;
            div.style.height = RADIUS + "px";
            div.style.width = RADIUS + "px";
          });

          body.appendChild(div);
          ballList.push(div);
        }

        const timer = setInterval(() => {
          ballList.map((ball) => {
            let RADIUS = parseInt(ball.style.height.split("px")[0]);
            let X_SPEED = ball.xspeed;
            let Y_SPEED = ball.yspeed;

            if (ball.offsetLeft + RADIUS > WIDTH || ball.offsetLeft < 0) {
              X_SPEED = -X_SPEED;
            }

            if (ball.offsetTop + RADIUS > HEIGHT || ball.offsetTop < 0) {
              Y_SPEED = -Y_SPEED;
            }

            ball.xspeed = X_SPEED;
            ball.yspeed = Y_SPEED;
            ball.style.left = ball.offsetLeft + X_SPEED + "px";
            ball.style.top = ball.offsetTop + Y_SPEED + "px";
          });
        }, 15);
      });
    </script>
  </body>
</html>