声明,该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"){//首先判断浏览器是否支持opacityif("opacity" in obj.style){obj.style.opacity = (current + step) / 100;}else{obj.style.filter = "alpha(opacity = " + (current + step) + ")";}//再判断属性是否为z-index}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这样常见的属性是必不可少的。利用该框架,可以实现非常棒的效果。所以现在开始正式做该DEMO。
首先是index.html的制作。
<div id="box"><ul><li></li><li></li><li></li><li></li><li></li></ul></div>
index.html的制作非常的简单,我们会将图片作为li的背景图片在javascript中进行插入。之后,我们进行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});}}}}这样使用原生JS实现的风箱效果demo就实现了,当然,还可以利用封装好的animate框架实现类似网易的轮播图效果。
以上这篇原生JS实现风箱式demo,并封装了一个运动框架(实例代码)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。