首页 > 解决方案 > 用滑动代替跳跃然后改变模式

问题描述

我的任务是使用现有代码在 javascript 中创建动画并进行更改以做两件事。切换模式,然后继续,直到该人关闭程序。四种模式是:

模式 0 - 从左到右

模式 1 - 从上到下

模式 2 - 从右到左

模式 3 - 自下而上

从模式 0 切换到 1 是麻烦开始的地方。它应该滑动,但当我到达那里时它会跳动。

下面是我的代码。

<!DOCTYPE html>
<html>
    <style>
        #container {
            width: 400px;
            height: 400px;
            position: relative;
            background: yellow;
        }
        #animate {
            width: 50px;
            height: 50px;
            position: absolute;
            background-color: red;
        }
     </style>
     <body>

     <p><button onclick="myMove()">Click Me</button></p> 

     <div id ="container">
         <div id ="animate"></div>
     </div>

     <script>
         function myMove() {
             var elem = document.getElementById("animate");   
             var pos = 350;
             var id = setInterval(frame, 5);
         }
         function frame() {
             if (pos == 0) {
                 pos++;
                 elem.style.bottom= pos + 'px';
             } else {
                 pos--;
                 elem.style.left = pos + "px"; 

                 if (pos == 49.985) {
                     pos++;
                     elem.style.left = pos + "px";
                 }
             }

标签: javascriptjquery

解决方案


我建议您对 x 和 y 使用两个变量,并将 posBottom 替换为 top 样式的变量。

之前的问题是 whenpos等于 0 并因此触发了 if 语句,它立即递增,导致它改为触发else,然后递减,回到if,等等。它跳起来是因为它style.bottom = 0px导致它直接下降到底部。

function myMove() {
  var elem = document.getElementById("animate");   
  var posLeft = 350;
  var posTop = 0;
  var id = setInterval(frame, 5);
  function frame() {
    if (posLeft == 0 && posTop != 350) {
      stage=1;
      posTop++;
      elem.style.top= posTop + 'px';
    } else if (posTop == 0) {
      posLeft--;
      elem.style.left = posLeft + "px"; 
    } else if (posLeft != 350) {
      posLeft++;
      elem.style.left = posLeft + "px";
    } else if (posTop != 0) {
      posTop--;
      elem.style.top= posTop + 'px';
    }
  }
}
#container {

  width: 400px;
  height: 400px;
  position: relative;
  background: yellow;
}
#animate {
width: 50px;
height: 50px;
position: absolute;
background-color: red;
}
<p><button onclick="myMove()">Click Me</button></p> 

<div id ="container">
<div id ="animate"></div>
</div>


推荐阅读