当前位置:网站首页>Small ball bouncing against the wall

Small ball bouncing against the wall

2022-06-26 02:10:00 Asmruan

<!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> Start </button>
    <button disabled> Pause </button>
  </body>
</html>
<script>
  var header = document.querySelector("header");
  var div = document.querySelector("div");
  var timer = null;
  //  Initial value 
  var x = 0;
  var y = 0;

  //  Direction 
  var addX = true;
  var addY = true;
  //  critical value   The width of the box  -  The diameter of the ball 
  var xMax = header.scrollWidth - div.offsetWidth;
  var yMax = header.scrollHeight - div.offsetHeight;

  document.querySelector("button").onclick = function () {
    //  Pause release 
    document.querySelectorAll("button")[1].disabled = false;
    this.disabled = true;

    timer = setInterval(function () {
      // div.style.left = num + "px"
      // div.style.top = num + "px"
      //  Specify an initial speed and direction 
      if (addX) {
        x++;
        //  Judge the warning value 
        if (x >= xMax) {
          //  At this time, the horizontal direction reaches the maximum value , Change direction 
          addX = false;
        } else {
          //  Horizontal assignment 
          div.style.left = x + "px";
        }
      } else {
        //  redirect 
        x--;
        //  Judge the warning value 
        if (x <= 0) {
          //  At this time, the horizontal direction reaches the maximum value , Change direction 
          addX = true;
        } else {
          //  Horizontal assignment 
          div.style.left = x + "px";
        }
      }

      //  vertical direction 
      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>

原网站

版权声明
本文为[Asmruan]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202180550383724.html