置顶 js弹力器

javascript

JavaScript

2020-05-15 12:06:29

408

作者:黑夜男神

弹力球关键逻辑在于当小球当前运动的坐标值到达临界点时再改变递增正负值来改变运动方向

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>弹力球</title>
</head>
<body>
  <div class="ball"></div>
  <script>

    let  ball = document.querySelector('.ball')
    let  ballX = 0;
    let  ballY = 0
    let  yv = 10 // 每次运动的X距离
    let  xv = 20 // 每次运动的Y距离
    let  WinH = document.documentElement.clientHeight - 100
    let  WinW = document.documentElement.clientWidth - 100
    function move () {
      ballY+= yv
      ballX+= xv
       if(ballY >= WinH) {
        yv=-yv // 关键点将原来的递增值改变为递减
       }
       if (ballY <=0) {
         yv=-yv // 再关键点将原来的递增值改变为递增 负负就是正
       }
       if (ballX > WinW) {
         xv =-xv
       }
       if (ballX <= 0) {
         xv=-xv
       }
      ball.style.left = ballX + 'px'
      ball.style.top = ballY + 'px'
      requestAnimationFrame(move)
     }
     requestAnimationFrame(move)
  </script>

  <style>
    *{
      margin: 0;
      padding: 0;
    }
    .ball {
      position: absolute;
      width: 100px;
      height: 100px;
      background: rgb(219, 22, 22);
      border-radius: 50%;
    }
  </style>
</body>
</html>

评论 (0)

用户名
邮箱
评论

    Copyright © 2020 darkNightMan All Rights Reserved Pro 黔ICP备20005477号