js运动小球碰壁反弹

8 篇文章 0 订阅
8 篇文章 0 订阅

js运动小球碰壁反弹

1、触碰窗口壁沿反弹,同时改变颜色

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>碰壁反弹</title>
  <style>
    #box {
      margin: 50px auto 0;
      width: 800px;
      height: 600px;
      border: 2px solid #ccc;
      position: relative;
    }

    #subbox {
      width: 50px;
      height: 50px;
      position: absolute;
      border-radius: 50%;
      top: 0;
      left: 0;
      background-color: lightblue;
    }
  </style>
</head>

<body>
  <div id="box">
    <div id="subbox"></div>
  </div>

</body>

</html>
<script>
  var box = document.getElementById('box');
  var subbox = document.getElementById('subbox');
  var leftMax = 800 - subbox.clientWidth;
  var topMax = 600 - subbox.clientHeight;
  // 定时器
  var lTor = null;
  // 每次变化的像素值
  var lengLeft = 5;
  var lengTop = 5;
  console.log(topMax);
  console.log(leftMax);
  function leftToRight() {

    var Left = subbox.offsetLeft + lengLeft;
    var Top = subbox.offsetTop + lengTop;

    if (Left >= leftMax) {
      Left = leftMax;
      lengLeft = -lengLeft;
      changeColor(subbox);

    } else if (Left <= 0) {
      Left = 0;
      lengLeft = -lengLeft;
      changeColor(subbox);

    };
    if (Top >= topMax) {
      Top = topMax;
      lengTop = -lengTop;
      changeColor(subbox);

    } else if (Top <= 0) {
      Top = 0;
      lengTop = -lengTop;
      changeColor(subbox);

    }
    subbox.style.top = Top + "px";
    subbox.style.left = Left + "px";
  }
  function changeColor(obj) {
    var a = Math.floor(Math.random() * 255);
    var b = Math.floor(Math.random() * 255);
    var c = Math.floor(Math.random() * 255);
    obj.style.background = "rgb(" + a + "," + b + "," + c + ")";
    return obj;
  }
  box.onclick = function () {
    // clearInterval(lTor);
    lTor = setInterval(function () {
      leftToRight();
    }, 25)
  }
</script>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值