js实现倒计时
很多场合用到倒计时,比如年会,生日,约会啊...废话不多说上代码
效果图:
index.html
<!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>
body{
background-color: #2a3852;
}
#box {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
margin-top: 300px;
}
#box h1 {
letter-spacing: 3px;
font-weight: 500;
color: #fff;
}
#time {
display: flex;
flex-direction: row;
line-height: 50px;
}
#time span {
font-size: 20px;
color: #fff;
}
#time span {
text-align: center;
margin-left: 20px;
background-color: #3f5174;
border-radius: 10px;
width: 70px;
height: 50px;
display: block;
}
</style>
</head>
<body>
<div id="box">
<h1>距离国庆节,还有</h1>
<div id="time">
<span id="day">**天</span>
<span><span id="hour">**时</span></span>
<span><span id="minute">**分</span></span>
<span><span id="second">**秒</span></span>
</div>
</div>
<script></script>
<script>
var daySpan = my$('day');
var hourSpan = my$('hour');
var minuteSpan = my$('minute');
var secondSpan = my$('second');
TimeRow();
setInterval(TimeRow, 1000)
function TimeRow() {
var end = new Date('2020-10-1 0:0:0');
var start = new Date();
var time = getInterval(start, end);
setInnerText(daySpan, time.day+'天');
setInnerText(hourSpan, time.hour+'时');
setInnerText(minuteSpan, time.minute+'分');
setInnerText(secondSpan, time.second+'秒');
}
</script>
</body>
</html>
common.js
function my$(id) {return document.getElementById(id);
}
// 处理innerText和textContent的兼容性问题
// 设置标签之间的内容
function setInnerText(element, content) {
// 判断当前浏览器是否支持 innerText
if (typeof element.innerText === 'string') {
element.innerText = content;
} else {
element.textContent = content;
}
}
function getInterval(start, end) {
// 两个日期对象,相差的毫秒数
var interval = end - start;
// 求 相差的天数/小时数/分钟数/秒数
var day, hour, minute, second;
// 两个日期对象,相差的秒数
// interval = interval / 1000;
interval /= 1000;
day = Math.round(interval / 60 / 60 / 24);
hour = Math.round(interval / 60 / 60 % 24);
minute = Math.round(interval / 60 % 60);
second = Math.round(interval % 60);
return {
day: day,
hour: hour,
minute: minute,
second: second
}
}
以上是 js实现倒计时 的全部内容, 来源链接: utcz.com/a/43081.html