【问题标题】:animation using javascript - how to move an object upwards使用 javascript 的动画 - 如何向上移动对象
【发布时间】:2018-04-07 18:48:36
【问题描述】:

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

    <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>

【问题讨论】:

标签: javascript


【解决方案1】:

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';
             }
      }
   } 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-09
    • 1970-01-01
    • 2013-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多