效果:
代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> div div { float: left; width: 30px; font-size: 120px; } #hours0,#hours1,#minute0,#minute1,#second0,#second1 { width: 200px; height: 165px; background-image: url("img/sztp.jpg"); } </style> </head> <body> <div> <div></div> <div></div> <div>:</div> <div></div> <div></div> <div>:</div> <div></div> <div></div> </div> <script> var hours0,hours1,minute0,minute1,second0,second1; var imgPositionList=[];//各数字的位置 init(); function init() { hours0=document.getElementById("hours0");//小时1 hours1=document.getElementById("hours1");//小时2 minute0=document.getElementById("minute0");//分钟1 minute1=document.getElementById("minute1");//分钟2 second0=document.getElementById("second0");//秒针1 second1=document.getElementById("second1");//秒针2 for(var i=0;i<10;i++){ //循环赋值各数字的位置 if(i<5){ //第一排 imgPositionList.push({x:-i*208,y:0}); continue; } imgPositionList.push({x:-(i-5)*208,y:-173}) //第二排 } console.log( imgPositionList); imgPositionList.unshift(imgPositionList.pop());//将0 :最末尾的图片 删除 ,返回的值提到最前面。 setInterval(animation,16); } function animation() { var date=new Date(); var hour=date.getHours().toString().split("").map(function (t) { return getNum(t) }); var minutes=date.getMinutes().toString().split("").map(function (t) { return getNum(t) }); var seconds=date.getSeconds().toString().split("").map(function (t) { return getNum(t) }); getDoubleArr(hour); getDoubleArr(minutes); getDoubleArr(seconds); setTimeDiv(hours0,hour[0]); setTimeDiv(hours1,hour[1]); setTimeDiv(minute0,minutes[0]); setTimeDiv(minute1,minutes[1]); setTimeDiv(second0,seconds[0]); setTimeDiv(second1,seconds[1]); } function getDoubleArr(arr) { //字符串转化数组 if(arr.length===1) arr.unshift(0); return arr; } function setTimeDiv(elem,num) { //时间与图片的对应 clone(elem.style,{ backgroundPositionX: imgPositionList[num].x+"px", backgroundPositionY: imgPositionList[num].y+"px" }); } function getNum(str) { if(isNaN(Number(str))) return str; return Number(str); } function clone(target,source) { for(var key in source){ target[key]=source[key]; } } </script> </body> </html>