对于很多网页和很多生活中的地方,都会用到计时器,那么这个准确来计时的东西是怎么写出来的呢,今天带大家写一个简单的计时器。
css和html页面搭建
<h1 class="title">距离2022元旦,还有</h1>
<div class="time-item">
<span><span id="day">00</span>天</span>
<strong><span id="hour">00</span>时</strong>
<strong><span id="minute">00</span>分</strong>
<strong><span id="second">00</span>秒</strong>
</div>
* {
margin: 0;
padding: 0;
}
.time-item {
width: 450px;
height: 45px;
margin: 0 auto;
}
.time-item strong {
background: orange;
color: #fff;
line-height: 49px;
font-size: 36px;
font-family: Arial;
padding: 0 10px;
margin-right: 10px;
border-radius: 5px;
box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.2);
}
.time-item>span {
float: left;
line-height: 49px;
color: orange;
font-size: 32px;
margin: 0 10px;
font-family: Arial, Helvetica, sans-serif;
}
.title {
width: 330px;
height: 50px;
margin: 200px auto 50px auto;
}
//主要原理就是 用 newDate - oldDate得到得时间
var day = document.getElementById('day')
var hour = document.getElementById('hour')
var minute = document.getElementById('minute')
var second = document.getElementById('second')
setInterval(function() {
var now = new Date()
var gettime = new Date('2022-1-1 0:0:0')
var timeout = gettime - now
day.innerText = Math.floor(timeout / (1000 * 60 * 60 * 24))
hour.innerText = Math.floor(timeout / 1000 / 60 / 60 % 24)
minute.innerText = Math.floor(timeout / 1000 / 60 % 60)
second.innerText = Math.floor(timeout / 1000 % 60)
}, 1000)
效果展示
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.time-item {
width: 450px;
height: 45px;
margin: 0 auto;
}
.time-item strong {
background: skyblue;
color: #fff;
line-height: 49px;
font-size: 36px;
font-family: Arial;
padding: 0 10px;
margin-right: 10px;
border-radius: 5px;
box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.2);
}
.time-item>span {
float: left;
line-height: 49px;
color: skyblue;
font-size: 32px;
margin: 0 10px;
font-family: Arial, Helvetica, sans-serif;
}
.title {
width: 330px;
height: 50px;
margin: 200px auto 50px auto;
}
</style>
</head>
<body>
<h1 class="title">距离2022年元旦</h1>
<div class="time-item">
<span><span id="day">00</span>天</span>
<strong><span id="hour">00</span>时</strong>
<strong><span id="minute">00</span>分</strong>
<strong><span id="second">00</span>秒</strong>
</div>
<script>
var day = document.getElementById('day')
var hour = document.getElementById('hour')
var minute = document.getElementById('minute')
var second = document.getElementById('second')
setInterval(function() {
var now = new Date()
var gettime = new Date('2022-1-1 0:0:0')
var timeout = gettime - now
day.innerText = Math.floor(timeout / (1000 * 60 * 60 * 24))
hour.innerText = Math.floor(timeout / 1000 / 60 / 60 % 24)
minute.innerText = Math.floor(timeout / 1000 / 60 % 60)
second.innerText = Math.floor(timeout / 1000 % 60)
}, 1000)
</script>
</body>
</html>