计时器的简单应用
双11将至!今天给大家写一个简单的计时器来显示距离双11的时间
效果如下:
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.time-item {
width: 430px;
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: 260px;
height: 50px;
margin: 200px auto 50px auto;
}
.bg {
width: 700px;
height: 700px;
background-color: aqua;
border-radius: 50%;
position: relative;
margin: 100px auto;
box-sizing: border-box;
padding-top: 80px;
}
.content {}
</style>
</head>
<body>
<div class="bg">
<div class="content">
<h1 class="title">距双11,还有</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>
</div>
</div>
<script>
//获取元素
var day = document.getElementById('day')
var hour = document.getElementById('hour')
var minute = document.getElementById('minute')
var second = document.getElementById('second')
var endtime = new Date('2020-11-11 0:0:0')
fn()
setInterval(fn, 1000) //定时器
function fn() {
var totaltime = (endtime - new Date()) / 1000//计算输入时间与当前时间的差量(毫秒)
var d = parseInt(totaltime / 60 / 60 / 24)//计算日期:几号
var h = parseInt(totaltime / 60 / 60 % 24)//计算小时数
var m = parseInt(totaltime / 60 % 60)//计算分钟数
var s = parseInt(totaltime % 60)//计算秒数
//将获取内容添加至对应元素中
day.innerText = d > 10 ? d : '0' + d
hour.innerText = h > 10 ? h : '0' + h
minute.innerText = m > 10 ? m : '0' + m
second.innerText = s < 10 ? '0' + s : s
}
</script>
</body>
</html>