使用javascript动画 - 如何向上移动对象

时间:2017-10-26 11:43:46

标签: javascript

以下是我的代码,容器盒内有一个小盒子,点击按钮,它向下动画并击中容器的底部,然后它应该从那里升起。但相反,它开始在同一个地方快速闪烁。请告诉我如何将盒子撞到底部时将其抬起。

    <style>
        #myContainer {
        width: 400px;
        height: 400px;
        position: relative;
        background: yellow;
       }
      #myAnimation {
        width: 50px;
       height: 50px;
       position: absolute;
       background: red;
      }
 </style>
  <p>
      <button id=button>Click Me</button> 

 </p>

  <div id ="myContainer">
         <div id ="myAnimation">Fish</div>
   </div>

  <script>
   button =document.getElementById("button");
   button.onclick = function() {
var elem = document.getElementById("myAnimation");
var pos = 0;
var id = setInterval(frame, 10);
function frame() {
    /*if (pos == 350) {
        clearInterval(id);
    } 
    else*/

        if(pos<175)

    {
        pos++;
        elem.style.top = 2*pos + 'px';
        elem.style.left = pos + 'px';
    }
    else
    {
            pos--;
        elem.style.top = pos + 'px';
        elem.style.right = pos + 'px';
             }
      }
   } 
   </script>

1 个答案:

答案 0 :(得分:0)

made一个小小的解决方案,你需要一个开关组成直到顶部,然后再到底部。

button =document.getElementById("button");
   button.onclick = function() {
var elem = document.getElementById("myAnimation");
var pos = 0, up=false;
var id = setInterval(frame, 10);

function frame() {
console.log(up, pos);
    /*if (pos == 350) {
        clearInterval(id);
    } 
    else*/

        if(pos<175 && !up)

    {
        pos++;
        if(pos===175) up=true;
        elem.style.top = pos + 'px';
        elem.style.left = pos + 'px';
    }
    else
    {
            pos--;
            if(pos<=0) up=false;
        elem.style.top = pos + 'px';
        elem.style.left = pos + 'px';
             }
      }
   }