如下所示:
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <style> div { width: 100px; height: 100px; background-color: pink; position: absolute; left: 0; top: 50px; border-radius: 50%; } </style> </head> <body> <button id="btn200">200</button> <button id="btn400">400</button> <div id="box"></div> </body> </html> <script> var btn200 = document.getElementById("btn200"); var btn400 = document.getElementById("btn400"); var box = document.getElementById("box"); btn200.onclick = function() { animate(box,{width: 200, top: 100,left: 200,opacity:40,zIndex:3},function(){alert("我來了")}); } btn400.onclick = function() { animate(box,{top:500,opacity:10}); } // 多個屬性運動框架 添加回調函數 function animate(obj,json,fn) { // 給誰 json clearInterval(obj.timer); obj.timer = setInterval(function() { var flag = true; // 用來判斷是否停止定時器 一定寫到遍歷的外面 for(var attr in json){ // attr 屬性 json[attr] 值 //開始遍歷 json // 計算步長 用 target 位置 減去當前的位置 除以 10 // console.log(attr); var current = 0; if(attr == "opacity") { current = Math.round(parseInt(getStyle(obj,attr)*100)) || 0; console.log(current); } else { current = parseInt(getStyle(obj,attr)); // 數值 } // console.log(current); // 目標位置就是 屬性值 var step = ( json[attr] - current) / 10; // 步長 用目標位置 - 現在的位置 / 10 step = step > 0 ? Math.ceil(step) : Math.floor(step); //判斷透明度 if(attr == "opacity") // 判斷用戶有沒有輸入 opacity { if("opacity" in obj.style) // 判斷 我們瀏覽器是否支持opacity { // obj.style.opacity obj.style.opacity = (current + step) /100; } else { // obj.style.filter = alpha(opacity = 30) obj.style.filter = "alpha(opacity = "+(current + step)* 10+")"; } } else if(attr == "zIndex") { obj.style.zIndex = json[attr]; } else { obj.style[attr] = current + step + "px" ; } if(current != json[attr]) // 只要其中一個不滿足條件 就不應該停止定時器 這句一定遍歷里面 { flag = false; } } if(flag) // 用于判斷定時器的條件 { clearInterval(obj.timer); //alert("ok了"); if(fn) // 很簡單 當定時器停止了。 動畫就結束了 如果有回調,就應該執行回調 { fn(); // 函數名 + () 調用函數 執行函數 } } },30) } function getStyle(obj,attr) { // 誰的 那個屬性 if(obj.currentStyle) // ie 等 { return obj.currentStyle[attr]; // 返回傳遞過來的某個屬性 } else { return window.getComputedStyle(obj,null)[attr]; // w3c 瀏覽器 } } </script>
以上這篇原生JS封裝animate運動框架的實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com