本文实例为大家分享了javascript实现简单页面倒计时的具体代码,供大家参考,具体内容如下
话不多说,直接贴代码
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
|
<!DOCTYPE html> < html > < head > < meta charset = "utf-8" > < style type = "text/css" > body { color:red; text-align: center; } .one{ color:black; text-align:center; } </ style > </ head > < body > < p > 日期倒计时< br > 请输入目标日期并点击按钮,实现目标日期的倒计时! </ p > < form name = "form1" > < input type = "text" id = "a" size = 1 name = "a" >年 < input type = "text" id = "b" size = 1 name = "b" >月 < input type = "text" id = "c" size = 1 name = "c" >日 < input type = "text" id = "d" size = 1 name = "d" >时 < input type = "text" id = "e" size = 1 name = "e" >分 < input type = "text" id = "f" size = 1 name = "f" >秒 < br > < div id = "time" value = "时间" ></ div > < script > function getdate(clock){ var now=new Date(); var y=now.getFullYear() var m=now.getMonth() var d=now.getDate() var day=now.getDay() var h=now.getHours() var minu=now.getMinutes() var s=now.getSeconds() m+=1; var array=new Array("星期日","星期一","星期二","星期三","星期四","星期五","星期六") var nowtime=y+"年"+m+"月"+d+"日 "+array[day]+" "+h+"时"+minu+"分"+s+"秒"; clock.innerHTML="当前时间:"+nowtime; } window.onload=function(){ window.setInterval("getdate(time)",1000) } </ script > < input type = "button" value = "倒计时" onclick = "leftTime()" >: 距离目标日期还有: < input type = "text" id = "cha" > < script > var flag=1;var t; function leftTime(){ if(flag==0){flag=1;} year=document.getElementById("a").value; month=document.getElementById("b").value; day=document.getElementById("c").value; hour=document.getElementById("d").value; minute=document.getElementById("e").value; second=document.getElementById("f").value; var leftTime = (new Date(year,month-1,day,hour,minute,second)) - (new Date()); //计算剩余的毫秒数 if(leftTime>0){ var days = parseInt(leftTime/1000/60/60/24,10); //计算剩余的天数 var hours = parseInt(leftTime/1000/60/60%24,10); //计算剩余的小时 var minutes = parseInt(leftTime/1000/60%60,10);//计算剩余的分钟 var seconds = parseInt(leftTime/1000%60,10);//计算剩余的秒数 document.getElementById("cha").value=days+"天" + hours+"小时" + minutes+"分"+seconds+"秒"; } else{ document.getElementById("cha").value="0天0小时0分0秒"; alert("主人,时间到啦!") flag=0;clearInterval(t); } if(flag==1){ t=setInterval("leftTime()",1000); flag=2; } } </ script > </ form > </ body > </ html > |
第一次写完测试的时候,发现时间到了之后页面一直不断弹出提示框,后面百度了下发现每调用一次setInterval周期性调用函数就要设置一次clearInterval来关闭,于是通过设置flag来实现;最终代码如上所示。运行结果如下:
时间到:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/weixin_36413887/article/details/77816333