首頁  >  文章  >  web前端  >  js動畫學習(一)

js動畫學習(一)

黄舟
黄舟原創
2016-12-30 16:54:011092瀏覽

一、運動框架實現想法

1.勻速運動(屬性值勻速變化)(改變left, right, width, height, opacity 等);

2.緩衝運動(屬性值的變化速度與當前值與目標值的差成正比);

3.多物體運動;

4.任意屬性值的變化(用封裝函數);

5.鍊式運動(同一物體完成一系列的運動);

6 .多物體同時移動

============================================ =========

二、簡單運動之勻速運動

下面的函數就是運動系列函數的基本框架。

//鼠标移到元素上元素右移,鼠标离开元素回去。 
    var timer="";
    function Move(speed,locat) {//移动速度,移动终点位置
        var ob=document.getElementById('box1');
        clearInterval(timer);//先清除定时器,防止定时器的嵌套调用
        timer=setInterval(function () {
            if (ob.offsetLeft==locat) {//当前位置到达指定终点,关闭定时器
                clearInterval(timer);
            } else {//否则元素的left属性等于当前left加上每次改变的速度
               ob.style.left=ob.offsetLeft+speed+'px';
           }
        }, 30)
    }

舉個栗子:

在下面的HTML文檔中調用上面的JS函數

<style type="text/css">
     *{
         margin: 0;
         padding: 0;
     }
     
     #box1{
         width: 200px;
         height: 200px;
         background-color: red;
         position: absolute;
         left: 0;
     }
  </style>
<div id="box1"></div>
 <script type="text/javascript">
     window.onload=function(){
         var ob=document.getElementById(&#39;box1&#39;);
         ob.onmouseover=function(){
             Move(10,200);//鼠标移到div上时div从0移到200
         }  
         ob.onmouseout=function(){
             Move(-10,0);//鼠标移走时div从200移到0
         }  
     }
 </script>

三、簡單動畫之改變透明度


函數的模型和上一節基本一致,不同的是元素沒有自身透明度屬性,需要先把透明度初值定義好。

1 var timer="";
 2 var alpha=30;//透明度初始值
 3 function changeOpacity(speed,target) {
 4     var div1=document.getElementById(&#39;div1&#39;);//获取改变透明度的元素
 5     clearInterval(timer);//清除定时器,避免嵌套调用
 6     timer=setInterval(function () {
 7         if (alpha==target) {//如果透明度达到目标值,清除定时器
 8             clearInterval(timer);
 9         } else {//当前透明度加上透明度变化的速度
10             alpha=alpha+speed;
11             div1.style.filter=&#39;alpha(opacity:&#39;+alpha+&#39;)&#39;;//IE浏览器
12             div1.style.opacity=alpha/100; //火狐和谷歌
13         }
14     }, 30)
15 }

在下面的HTML文件中引用上面的JS函數,實現透明度的改變

1 <style type="text/css">
 2     *{
 3         margin: 0;
 4         padding: 0;
 5     }
 6     #div1{
 7         width: 200px;
 8         height: 200px;
 9         background: red;
10         filter: alpha(opacity:30);/*filter滤镜:不透明度,IE浏览器*/ 
11         opacity: 0.3;/*火狐和谷歌*/
12     }
13 </style>
1 <div id="div1"></div>
 2 <script type="text/javascript">
 3     window.onload=function(){
 4         var div1=document.getElementById(&#39;div1&#39;);
 5         div1.onmouseover=function(){
 6             changeOpacity(10,100);
 7         }
 8         div1.onmouseout=function(){
 9             changeOpacity(-10,30);
10         }
11     }

 以上就是js動畫學習(一)的內容,更多相關內容請關注PHP中文網(www.php.cn)!


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn