Javascript动态显示时间

By yesmore on 2021-07-21
阅读时间 1 分钟
文章共 262
阅读量

知识点

Timing事件之 setInterval()方法:

效果

上代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>

</style>
</head>
<body>

<div id="time"></div>
<input type="button" value="开始" id="start"></input>
<input type="button" value="结束" id="end"></input>
</body>

<script type="text/javascript">
window.onload = function(){


var start = document.getElementById('start');
var end = document.getElementById('end');
var time1 = document.getElementById('time');

start.onclick = function(){

// clearInterval(timer);

timer = setInterval(function(){

var d = new Date();
// 年月日
var year = d.getFullYear();
var month = d.getMonth()+1;
var day = d.getDate();
// 时分秒
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
if(s<10){
s = "0"+s;
}
// time1.innerHTML = s;
time1.innerHTML = "当前时间:"+year+"-"+month+"-"+day+" "+h+":"+m+":"+s;

},100);

end.onclick = function(){
clearInterval(timer);
// alert('stop');
};
};

};
</script>
</html>

Tips: Please indicate the source and original author when reprinting or quoting this article.