9.1定时器 小时分秒

功能:用切换图片0-9效果显示当前系统时间

属性:img的src

1.用到

new Date()

getHours(),getMinutes(),getSeconds()

getFullyear(),getMouth()+1月数需要加1,getDay()星期为0,1,2,3,4,5,6

2.单位数转换成双位字符串的函数

function toDou(n){

if(n<10){

return '0'+n;//任意数加字符串结果为字符串的拼接

}

else{

return ' '+n;//任意数加空字符串结果为字符串

}

}

3.获取字符串用str.charAt(i),否则不兼容

4.计时器

开启setInterval(fn,时间)无限循环,setTimeout(fn,时间)只执行一次

关闭clearInterval(),clearTimeout()

关闭方式:

var timer=null;

timer=setInterval(fn,时间);

clearInterval(timer);

5.获取系统时间转化成6位字符串

var str=toDou(oDate.getHours())+toDou(oDate.getMinutes())+toDou(oDate.getSeconds)

6.改变图片路径

aImag[i].src='img/'+str.charAt(i)+'.png'

7.setInterval(fn,时间)是时间后执行fn,显示会有些问题,为了一开始就执行fn,

代码顺序:

fn(...);

setInterval(fn,时间);

fn();

///////////////

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Examples</title>
<meta name="description" content="">
<meta name="keywords" content="">

<link href="css1.css" rel="stylesheet" type="text/css"
charset="UTF-8">
</head>
<body>
<div id="div1">
<img src="img/0.png"/>
<img src="img/0.png"/>
:
<img src="img/0.png"/>
<img src="img/0.png"/>
:
<img src="img/0.png"/>
<img src="img/0.png"/>
</div>
<script src="js1.js"> </script>
</body>
</html>

////////////////css

body{
background :#000;
font-size: 50px;
}
#div1{
background:#fff;
680px;
height:110px;
padding:0;
margin-top:50px;
margin-left:20%;
text-align: center;
}
img{
72px;
height:85px;
margin-top:10px;

}

/////////////////js

window.onload=function(){
function gogo(){
var oDate=new Date();
var aImg=document.getElementsByTagName("img");
function toDou(n){
if(n<10){
return '0'+n;
}
else{
return ''+n;
}
};
var str=toDou(oDate.getHours())+toDou(oDate.getMinutes())+toDou(oDate.getSeconds());
for(var i=0;i<aImg.length;i++){
aImg[i].src='img/'+str.charAt(i)+'.png';
}};
setInterval(gogo,1000);
gogo();
};

原文地址:https://www.cnblogs.com/luxiaoli/p/8515993.html