1. 程式人生 > >9.1定時器 小時分秒

9.1定時器 小時分秒

ets enter 當前系統時間 style function chrom art href idt

功能:用切換圖片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;
width:680px;
height:110px;
padding:0;
margin-top:50px;
margin-left:20%;
text-align: center;
}
img{
width: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();
};

9.1定時器 小時分秒