滑动图片时钟
HTML
<ul id="box"> <li> <div> <img src="img/0.png"/> <img src="img/0.png"/> </div> </li> <li> <div> <img src="img/0.png"/> <img src="img/0.png"/> </div> </li> <li> <i></i> </li> <li> <div> <img src="img/0.png"/> <img src="img/0.png"/> </div> </li> <li> <div> <img src="img/0.png"/> <img src="img/0.png"/> </div> </li> <li> <i></i> </li> <li> <div> <img src="img/0.png"/> <img src="img/0.png"/> </div> </li> <li> <div> <img src="img/0.png"/> <img src="img/0.png"/> </div> </li> </ul>
CSS
*{ margin: 0; padding: 0; } ul{ height: 100px; margin: 50px 0 0 100px; overflow: hidden; } #box li{ width: 80px; height: 100px; position: relative; float: left; list-style: none; } #box div{ width: 80px; position: absolute; left: 0; top: 0; } img{ width: 80px; height: 100px; display: block; vertical-align: top; } i{ display: block; width: 80px; height: 100px; background: url(img/radio.png) no-repeat; background-size: 100% 100%; opacity: 1; }
JS
var oBox=document.getElementById("box"); var aDiv=oBox.getElementsByTagName("div"); var aImg=document.getElementsByTagName("img"); var is=document.getElementsByTagName("i"); var imgArray=["img/0.png","img/1.png","img/2.png","img/3.png","img/4.png","img/5.png","img/6.png","img/7.png","img/8.png","img/9.png","img/radio.png"]; //页面一打开获取的时间 var oldTimer=getTimer(); for (var i=0;i<oldTimer.length;i++) { aImg[i*2].src=imgArray[oldTimer[i]]; } setInterval(function(){ //不断更新的时间 var newTime=getTimer(); for (var i=0;i<newTime.length;i++) { //拿上次的时间和这次的时间进行对比,如果有变化就切换图片 if(oldTimer[i] != newTime[i]){ slied(i,newTime[i]); } //更新时间 } oldTimer = newTime; },1000) //图片滑动实现 function slied(n,time){ var imgs =aDiv[n].getElementsByTagName('img'); imgs[1].src = imgArray[time]; moveTo(aDiv[n],'top',-100,10,function(){ imgs[0].src = imgArray[time]; aDiv[n].style.top=""; }); } //获取时间函数 function getTimer(){ var timer=new Date(); var s=timer.getSeconds(); var m=timer.getMinutes(); var h=timer.getHours(); var str=zero(h)+zero(m)+zero(s); return str; } //补零函数 function zero(n){ if(n<10){ return n="0"+n; }else{ return n=""+n; } } //点闪动 setInterval(function(){ setTimeout(function(){ for (var i=0;i<is.length;i++) { if(getStyle(is[i],"opacity")==1){ is[i].style.opacity=0; }else{ is[i].style.opacity=1; } } },500) },500) //运动函数 function moveTo(obj,attr,target,dir,endFn){ clearInterval(obj.timer); //解决dir正负的问题:当原始值小于目标值时dir为正值,否则为负值 dir=parseInt(getStyle(obj,attr))<target?dir:-dir; obj.timer=setInterval(function(){ var speed=parseInt(getStyle(obj,attr))+dir;//步长 //当元素到达目标点时,停在目标点停止运动 if(speed>target&&dir>0||speed<target&&dir<0){ speed=target; } obj.style[attr]=speed+"px"; //清除定时器 if(speed==target){ clearInterval(obj.timer); if(endFn){ endFn(); } } },30) } //获取元素样式函数 function getStyle(obj,attr){ if(obj.currentStyle){ return obj.currentStyle(attr); }else{ return getComputedStyle(obj)[attr]; } }