小球触壁反弹

本文介绍了一个使用HTML和CSS创建的动态小球,通过JavaScript实现球体在网页header区域内的移动,并可通过按钮控制其运动和暂停。代码展示了基础的前端交互和定位技术。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      header {
        width: 600px;
        height: 500px;
        border: 10px dashed red;
        position: relative;
      }
      div {
        width: 100px;
        height: 100px;
        background-color: blue;
        border-radius: 50%;
        position: absolute;
      }
      button {
        font-size: 30px;
        padding: 6px 10px;
      }
    </style>
  </head>
  <body>
    <header>
      <div></div>
    </header>
    <button>开始</button>
    <button disabled>暂停</button>
  </body>
</html>
<script>
  var header = document.querySelector("header");
  var div = document.querySelector("div");
  var timer = null;
  // 初始值
  var x = 0;
  var y = 0;

  // 方向
  var addX = true;
  var addY = true;
  // 临界值 盒子宽度 - 球的直径
  var xMax = header.scrollWidth - div.offsetWidth;
  var yMax = header.scrollHeight - div.offsetHeight;

  document.querySelector("button").onclick = function () {
    // 暂停放开
    document.querySelectorAll("button")[1].disabled = false;
    this.disabled = true;

    timer = setInterval(function () {
      // div.style.left = num + "px"
      // div.style.top = num + "px"
      // 规定一个初始速度还有方向
      if (addX) {
        x++;
        // 判断警戒值
        if (x >= xMax) {
          // 此时水平方向达到最大值,改更改方向
          addX = false;
        } else {
          // 水平方向赋值
          div.style.left = x + "px";
        }
      } else {
        // 更改方向
        x--;
        // 判断警戒值
        if (x <= 0) {
          // 此时水平方向达到最大值,改更改方向
          addX = true;
        } else {
          // 水平方向赋值
          div.style.left = x + "px";
        }
      }

      // 垂直方向
      if (addY) {
        y+=10;
        if (y >= yMax) {
          addY = false;
        } else {
          div.style.top = y + "px";
        }
      } else {
        y--;
        if (y <= 0) {
          addY = true;
        } else {
          div.style.top = y + "px";
        }
      }
    }, 1);
  };


  document.querySelectorAll("button")[1].onclick = function () {
    document.querySelector("button").disabled = false;
    this.disabled = true;
    clearInterval(timer);
  };
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值