標籤:
聲明,該DEMO依託於某個培訓機構中,非常感謝這個培訓結構。話不多說,現在開始改demo的製作。
首先,在前端的學習過程中,輪播圖是我們一定要學習的,所以為了更加高效的實現各種輪播圖,封裝了一個運動的架構。
1 function getStyle(obj,attr) { 2 if(obj.currentStyle){ 3 return obj.currentStyle[attr];//為了擷取IE下的屬性值 4 }else{ 5 return window.getComputedStyle(obj,null)[attr];//為了擷取W3C瀏覽器下的屬性值 6 } 7 } 8 9 function animate(obj,json){10 clearInterval(obj.timer);11 obj.timer = setInterval(function () {12 var flag = true;13 var current = 0;14 for(var attr in json){15 if(attr == ‘opacity‘){16 current = parseInt(getStyle(obj,attr)*100);17 }else{18 current = parseInt(getStyle(obj,attr));19 };20 21 var step = (json[attr] - current) / 10;22 step = step > 0 ? Math.ceil(step) : Math.floor(step);23 //先判斷屬性是否為透明度24 if(attr == ‘opacity‘){25 //首先判斷瀏覽器是否支援opacity26 if(‘opacity‘ in obj.style){27 obj.style.opacity = (current + step) / 100;28 }else{29 obj.style.filter = ‘alpha(opacity = ‘ + (current + step) + ‘)‘;30 }31 //再判斷屬性是否為z-index32 }else if(attr == ‘zIndex‘){33 obj.style.zIndex = json[attr];34 //最後再判斷35 }else{36 obj.style[attr] = current + step + ‘px‘;37 }38 39 if(current != json[attr]){40 flag = false;41 }42 }43 44 if(flag){45 clearInterval(obj.timer);46 }47 },5);48 }
在該架構中相容了不同的瀏覽器,並且允許傳入opacity和z-index這樣的屬性,當然,像width,height,left,right這樣常見的屬性是必不可少的。利用該架構,可以實現非常棒的效果。所以現在開始正式做該DEMO。
首先是index.html的製作。
1 <div id="box">2 <ul>3 <li></li>4 <li></li>5 <li></li>6 <li></li>7 <li></li>8 </ul>9 </div>
index.html的製作非常的簡單,我們會將圖片作為li的背景圖片在javascript中進行插入。之後,我們進行CSS樣式的調節。
1 *{ 2 margin:0px; 3 padding:0px; 4 } 5 #box{ 6 width:1300px; 7 height:400px; 8 margin:100px auto; 9 overflow: hidden;10 }11 #box ul{12 height:400px;13 width:1300px;14 }15 #box ul li{16 width:240px;17 height:400px;18 float:left;19 overflow: hidden;20 }
javascript的代碼如下:
1 window.onload = function () { 2 var box = document.getElementById(‘box‘); 3 var aLi = box.children[0].children; 4 for(var i=0;i<aLi.length;i++){ 5 aLi[i].style.backgroundImage = ‘url(‘ + ‘images/‘ + (i + 1) + ‘.jpg‘; 6 aLi[i].onmouseover = function(){ 7 for(var i=0;i<aLi.length;i++){ 8 animate(aLi[i],{width:100}); 9 }10 animate(this,{width:800});11 };12 aLi[i].onmouseout = function(){13 for(var i=0;i<aLi.length;i++){14 animate(aLi[i],{width:240});15 }16 }17 }18 }
這樣使用原生JS實現的風箱效果demo就實現了,當然,還可以利用封裝好的animate架構實作類別似網易的輪播圖效果。
使用原生JS實現一個風箱式的demo,並封裝了一個運動架構