簡單JS動畫之分享框實現教程

用JS實現最簡單的動畫,用setInterval(fun(),milltime); 其中fun()是每隔milltime毫秒執行一次的函數。 以下是簡陋效果圖,當鼠標在分享位置上時,紅色p將從瀏覽器邊上慢慢向右展示,當鼠標離開分享位置時,紅色p將慢慢向左隱藏

這裡寫圖片描述

詳細代碼:

    <body>
      <p id="p1" >
          <span id="share">分享</span>
      </p>
    </body>
<style type="text/css">
    *{
        padding: 0;
        margin: 0;
    }
    p{
        width: 200px;
        height: 200px;
        background-color: #f00;
        position: relative;
        left: -200px;
    }
    span{
        width: 30px;
        height: 50px;
        background-color: aqua;
        position: absolute;
        top: 70px;
        left: 200px;
        text-align: center;
    }
</style> 
 <script type="text/javascript"> 

      var p1 = document.getElementById("p1"); 

      var share = document.getElementById("share"); 

      var timer = null; 

      var speed = 0; 

      p1.onmouseover = function(){ 

          startMove(0); 

      } 

      p1.onmouseout = function(){ 

          startMove(-200); 

      } 

      var startMove = function(target) { 

          if(target >= 0){ 

              speed  = 10; 

          }else { 

              speed = -10; 

          } 

          clearInterval(timer); 

          timer = setInterval(function () { 

              if(p1.offsetLeft == target){ 

                  clearInterval(timer); 

              }else { 

                  p1.style.left = p1.offsetLeft + speed + "px"; 

              } 

          }, 30); 

      } 

</script> 

You May Also Like