聲明:本 DEMO 依托於某培訓機構的教學思路,特此致謝。下面開始這個 demo 的製作。
在前端學習中,輪播圖是必學內容。為了更高效地實現各種動效,我們先封裝一個通用的運動框架。
function getStyle(obj,attr) { if(obj.currentStyle){ return obj.currentStyle[attr];//為了獲取IE下的屬性值 }else{ return window.getComputedStyle(obj,null)[attr];//為了獲取W3C浏覽器下的屬性值 } } function animate(obj,json){ clearInterval(obj.timer); obj.timer = setInterval(function () { var flag = true; var current = 0; for(var attr in json){ if(attr == 'opacity'){ current = parseInt(getStyle(obj,attr)*100); }else{ current = parseInt(getStyle(obj,attr)); }; var step = (json[attr] - current) / 10; step = step > 0 ? Math.ceil(step) : Math.floor(step); if(attr == 'opacity'){ if('opacity' in obj.style){ obj.style.opacity = (current + step) / 100; }else{ obj.style.filter = 'alpha(opacity = ' + (current + step) + ')'; } }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); } },5); }這個框架兼容了不同瀏覽器,並支持傳入 opacity、z-index 以及 width、height、left、right 等常見屬性。它採用「緩動」思路:每次按 (目標值-當前值)/10 計算步長,逐步逼近目標,到達後清除定時器。有了它,製作各種動效都得心应手。下面正式做這個風箱效果 DEMO。
首先是 index.html:
<div id="box"> <ul> <li></li> <li></li> <li></li> <li></li> <li></li> </ul> </div>
結構非常簡單,我們會把圖片作為 li 的背景,在 JS 中動態插入。接著調節 CSS 樣式:
*{ margin:0px; padding:0px; } #box{ width:1300px; height:400px; margin:100px auto; overflow: hidden; } #box ul{ height:400px; width:1300px; } #box ul li{ width:240px; height:400px; float:left; overflow: hidden; }JavaScript 代碼如下:
window.onload = function () { var box = document.getElementById('box'); var aLi = box.children[0].children; for(var i=0;i<aLi.length;i++){ aLi[i].style.backgroundImage = 'url(' + 'images/' + (i + 1) + '.jpg'; aLi[i].onmouseover = function(){ for(var i=0;i<aLi.length;i++){ animate(aLi[i],{width:100}); } animate(this,{width:800}); }; aLi[i].onmouseout = function(){ for(var i=0;i<aLi.length;i++){ animate(aLi[i],{width:240}); } } } }核心邏輯:鼠標懸停某項時,先把所有項收窄到 100px,再讓當前項擴展到 800px,形成「風箱」般的伸縮效果;移出時全部恢復 240px。借助封裝好的 animate 框架,還可以實現類似網易那樣的輪播圖效果。以上就是用原生 JS 實現風箱式 demo 並封裝運動框架的完整過程,希望能給大家一個參考。