1. 程式人生 > >js之物體的多值運動

js之物體的多值運動

透明 int ble 封裝 get nts 之間 top click

js運動

作為剛入門的小白,js 運動可以說是一個不可避免的步驟,為了更好的節約效率,下面提供了一種不錯的封裝方法供大家借鑒

 1 // 獲取dom元素的attr屬性
 2 function getStyle(dom, attr){
 3     if(window.getComputedStyle){
 4         return window.getComputedStyle(dom, null)[attr];
 5     }else{
 6         return dom.currentStyle[attr]; // 兼容IE
 7     }
 8 }
 9 
10 // 元素運動
11
function startMove(dom, attrObj){ // 參數為目標元素 包含多中屬性的對象 12 clearInterval(dom.timer); 13 var iSpeed = null, // 速度 14 iCur = null; // 屬性 15 dom.timer = setInterval(function(){ 16 var bStop = true; // 鎖 17 for(var attr in attrObj){ 18 if( attr == ‘opacity‘){ 19 iCur = parseFloat(getStyle(dom, ‘opacity‘)) * 100; // 由於透明度的取值在0~1之間,將值擴大100倍來實行緩沖運動
20 }else{ 21 iCur = parseInt(getStyle(dom, attr)); 22 } 23 iSpeed = (attrObj[attr] - iCur) / 7; // 速度隨時間推移而減少,從而完成緩沖運動 24 iSpeed = iSpeed > 0 ? Math.ceil(iSpeed) : Math.floor(iSpeed); // 在js中,每次運動至少為1單位,這也是為什麽要將透明度放大的原因 25 if(attr == ‘opacity‘){
26 dom.style.opacity = (iCur + iSpeed) / 100; 27 }else{ 28 dom.style[attr] = iCur + iSpeed + ‘px‘; 29 } 30 if(iCur != attrObj[attr]){ 31 bStop = false; 32 } 33 if(bStop){ 34 clearInterval(dom.timer); // 當dom元素所有屬性的運動全部結束時,清除定時器 35 } 36 } 37 }, 30); 38 }

接下來舉例說明

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <meta name="viewport" content="width=device-width, initial-scale=1.0">
 6     <meta http-equiv="X-UA-Compatible" content="ie=edge">
 7     <title>Document</title>
 8     <style>
 9         #demo{
10             width: 100px;
11             height: 100px;
12             background-color: red;
13             position: absolute;
14             top: 0;
15             left: 0;
16             opacity: 1;
17         }
18     </style> 
19 </head>
20 <body>
21     <div id="demo"></div> 
22     <script src="./tools.js"></script>
23     <script>
24         var oDiv = document.getElementById(‘demo‘);
25         oDiv.onclick = function(){
26             startMove(this, {width: 400, height: 400, left: 200, top: 200, opacity: 50});
27         }
28     </script>
29 </body>
30 </html>

由於代碼量問題,這裏將函數放到了 tools.js 文件中,首先為 div 綁定一個點擊事件,然後調用函數 startMove,使其多個屬性值發生改變,看起來就像是運動一樣,是不是很簡單呢?祝各位在前段的道路上越走越遠,早日成為優秀的前段工程師。

js之物體的多值運動