1. 程式人生 > >運動模組最終封裝

運動模組最終封裝

運動模組的最終版

 //封裝getScroll函式
    //獲取瀏覽器向上滾動的距離
    function getScroll(obj) {
        obj = {
            left:window.pageXOffset||document.documentElement.scrollLeft||document.body.scrollLeft,
            top:window.pageYOffset||document.documentElement.scrollTop||document.body.scrollTop||0
        }
; return obj; } //獲取元素的樣式屬性 function getStyle(ele,attr) { if(window.getComputedStyle){ return window.getComputedStyle(ele,null)[attr]; }else{ return ele.currentStyle[attr]; } } function animateHandle(ele,json,fn) { let
current,target; clearInterval(ele.timer); ele.timer = setInterval(function () { let flag = true;//設定一個標誌位,假設全部到達目標 for(let attr in json){ if(attr === 'opacity'){ //獲取當前元素的透明度 let current = getStyle
(ele,attr)*100; //目標的透明度放大100倍 target = json[attr]*100; let step = (target-current)/10; step = step>0?Math.ceil(step):Math.floor(step); current += step; ele.style[attr] = current/100; }else if(attr === 'zIndex'){ ele.style[attr] = json[attr]; }else{ //如果為普通屬性 current = parseInt(getStyle(ele,attr)); //獲取當前屬性對應的目標值 target = json[attr]; let step = (target-current)/10; step = step>0?Math.ceil(step):Math.floor(step); current += step; ele.style[attr] = current+'px'; } //判斷是否到達目標 if(current!=target){ //未到達目標 flag = false; //不進行清理定時器 } } if(flag){ //到達目標,進行清理 clearInterval(ele.timer); if(fn){ fn();//呼叫回撥函式 } } }) } let btn1 = document.getElementById('btn1'); let btn2 = document.getElementById('btn2'); let dv = document.getElementById('dv'); btn1.onclick = function () { animateHandle(dv,{left:400,top:500,opacity:"0.4"},function(){ animateHandle(dv,{left:20,top:100,opacity:'0.9'}) }) } btn2.onclick = function () { animateHandle(dv,{left:800,top:600,opacity:"0.2"},function(){ animateHandle(dv,{left:20,top:100,opacity:'0.9'}) }) }