<!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>
.content {
height: 150px;
width: 300px;
background-color: #000;
color: #ccc;
font-size: 20px;
line-height: 150px;
text-align: center;
}
</style>
</head>
<body>
<input type="datetime-local" placeholder="输入活动时间" id="inp">
<input type="button" value="开始计时" onclick="begin()">
<input type="button" value="停止计时" onclick="stop()">
<div id="timer" class="content"></div>
</body>
<script>
var timer = document.getElementById('timer')
var timerFlag
function countDown(time) {
var nowTime = +new Date() //返回的是当前时间的总毫秒数
var inputTime = +new Date(time) //返回的是用户输入的时间的总的毫秒数
if (inputTime > nowTime) {
var times = (inputTime - nowTime) / 1000 //times是剩余时间总的秒数
var d = parseInt(times / 60 / 60 / 24) //天数
d = d < 10 ? '0' + d : d
var h = parseInt(times / 60 / 60 % 24) //小时数
h = h < 10 ? '0' + h : h
var m = parseInt(times / 60 % 60) //分钟数
m = m < 10 ? '0' + m : m
var s = parseInt(times % 60) //当前的秒
s = s < 10 ? '0' + s : s
return d + ':' + h + ':' + m + ':' + s
} else {
alert('输入正确的时间')
return false
}
}
function begin() {
var inpValue = document.getElementById('inp').value
timer.innerText = '暂无活动'
if (inpValue == '') {
alert('输入活动时间')
return
}
timerFlag = setInterval(() => {
if (countDown(inpValue)) {
timer.innerText = countDown(inpValue)
} else {
clearInterval(timerFlag)
}
}, 1000)
}
function stop() {
clearInterval(timerFlag)
timer.innerText = "暂无活动"
}
</script>
</html>
输入一个时间,然后开始倒计时
最新推荐文章于 2023-04-01 16:29:22 发布