<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>时间对象</title>
<style>
#countdown {
margin-top: 20px;
}
#countdown span {
display: inline-block;
width: 40px;
height: 40px;
line-height: 40px;
margin-left: 10px;
margin-right: 10px;
vertical-align: middle;
font-size: 16px;
text-align: center;
color: white;
background-color: black;
}
</style>
</head>
<body>
<div>
<button onclick="init()">获取时间</button>
<div id="countdown">
<span id="day"></span>天
<span id="hour"></span>小时
<span id="min"></span>分钟
<span id="second"></span>秒
</div>
</div>
<script>
function init () {
getTime() // 点击按钮,先调用一次,避免一秒之后在触发定时器
setInterval(getTime, 1000)
}
function getTime () {
const newTime = new Date().getTime()
const loveTime = new Date('2023.01.29 17:05:00').getTime()
const surplusTime = (loveTime - newTime) / 1000 // 剩余时间秒数
if (surplusTime > 0) { // 倒计时存在
var oday = parseInt(surplusTime / 60 / 60 / 24) // 剩余天数
var ohours = parseInt(surplusTime / 60 / 60 - oday * 24) // 剩余小时数
var omin = parseInt(surplusTime / 60 - ohours * 60 - oday * 60 * 24) // 剩余分钟数
var osecond = parseInt(surplusTime - omin * 60 - ohours * 60 * 60 - oday * 60 * 60 * 24) // 剩余秒数
// 补零
oday < 10 ? oday = '0' + oday : oday
ohours < 10 ? ohours = '0' + ohours : ohours
omin < 10 ? omin = '0' + omin : omin
osecond < 10 ? osecond = '0' + osecond : osecond
document.getElementById('day').innerHTML = oday
document.getElementById('hour').innerHTML = ohours
document.getElementById('min').innerHTML = omin
document.getElementById('second').innerHTML = osecond
//1000表示每隔一秒变化一次,单位为毫秒
} else {
document.getElementById('countdown').innerHTML = '情人节快乐🎉'
clearInterval(getTime)
}
}
</script>
</body>
</html>```
原生JS倒计时
最新推荐文章于 2024-03-01 16:15:09 发布