使用原生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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
|
// An highlighted block
<!DOCTYPE html>
<html>
<head>
<meta charset= "utf-8" >
<title></title>
<!-- css样式 -->
<style type= "text/css" >
* {
margin: 0;
padding: 0;
}
.onsell {
height: 400px;
width: 200px;
border: 1px solid #F2F2F2;
margin: 10px;
box-shadow: 1px 2px 4px rgba(0, 0, 0, .2);
}
.box {
/* display: none; */
float: left;
margin: 328px 34px 0;
}
.box div {
position: relative;
display: inline-block;
width: 40px;
height: 40px;
background-color: #333;
color: #fff;
font-size: 20px;
text-align: center;
line-height: 40px;
box-shadow: 1px 2px 4px rgba(0, 0, 0, .4);
}
</style>
</head>
<body>
<!-- 要求:某商品在将来某一天进行促销一天,利用js制作倒计时效果: 时:分:秒 -->
<div class= "onsell" >
<div class= "box" >
<div class= "hour" >00</div>
<div class= "minutes" >00</div>
<div class= "seconds" >00</div>
</div>
</div>
</body>
</html>
<script>
window.onload = function () {
let hour = document.querySelector( '.hour' )
let minutes = document.querySelector( '.minutes' )
let seconds = document.querySelector( '.seconds' )
// 倒计时的时间戳 使用+将时间对象转为时间戳 等同于Date.now()
let wantTime = + new Date( '2021-3-17 18:00:00' )
countTime()
let timer = setInterval(() => {
countTime()
}, 1000)
function countTime() {
let currentTime = + new Date()
if (wantTime >= currentTime) {
let times = (wantTime - currentTime) / 1000 // 总秒数 时间戳/1000 = 秒
let remainDay = parseInt(times / 60 / 60 / 24) // 余数取整就是剩余的天数
console.log(remainDay);
if (remainDay === 0) {
if (times < 1) {
// 倒计时完毕
// 这里触发操作
}
// 天数小于一天开始计时
setTime(times)
}
} else {
hour.innerHTML = '00'
minutes.innerHTML = '00'
seconds.innerHTML = '00'
}
}
function setTime(time) {
// 粗糙版
let s = parseInt(time % 60)
s = s < 10 ? '0' + s : s
let m = parseInt(time / 60 % 60)
m = m < 10 ? '0' + m : m
let h = parseInt(time / 60 / 60 % 24)
h = h < 10 ? '0' + h : h
hour.innerHTML = h
minutes.innerHTML = m
seconds.innerHTML = s
}
}
</script>
|
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/qq_43122496/article/details/114941005