CONNLY-J / cultivate

0 stars 0 forks source link

实现物体移动 #23

Open goldEli opened 4 years ago

goldEli commented 4 years ago

用js实现物体往复运动,具体效果如下:

Untitled

完善以下代码

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>物体移动</title>
  <style>
    body{
      position: relative;
    }
    .box{
      width: 100px;
      height: 100px;
      background-color: red;
      position: absolute;
      top: 0;
      left: 0;
    }
  </style>
</head>
<body>
  <div id="js-box" class="box"></div>
  <script>
    // 用js实现,box 的往复运动
  </script>
</body>
</html>
CONNLY-J commented 4 years ago
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>物体移动</title>
  <style>
    body{
      position: relative;
    }
    .box{
      width: 100px;
      height: 100px;
      background-color: red;
      position: absolute;
      top: 0;
      left: 0;
    }
  </style>
</head>
<body>
  <div id="js-box" class="box"></div>
  <script>
    // 用js实现,box 的往复运动
    var speed = 5
    var div = document.getElementById('js-box')
    // 当前移动距离
    var currentDistance = 0
    // 最大移动距离
    var maxDistance = parseFloat('200px')
    setInterval(function() {
        if (currentDistance >= 0 && currentDistance <= maxDistance) {
            speed = speed
        }
        if(currentDistance < 0 ||currentDistance >maxDistance){
          speed = -speed
        }
        currentDistance += speed
        div.style.left =currentDistance + speed +'px'
    }, 100)
  </script>
</body>
</html>