<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
.box {
position: absolute;
left: 50%;
top: 50%;
transform: translate3d(-50%, -50%, 0);
background: pink;
width: 500px;
height: 200px;
text-align: center;
}
h1 {
margin-top: 30px;
text-align: center;
margin-bottom: 50px;
}
.box strong {
font-size: 30px;
background: orange;
border-radius: 5px;
padding: 5px 10px;
margin:0 10px;
}
</style>
</head>
<body id="bd">
<div class="box">
<h1>距离爱玲生日,还有</h1>
<strong><span id="s1"></span>天</strong>
<strong><span id="s2"></span>时</strong>
<strong><span id="s3"></span>分</strong>
<strong><span id="s4"></span>秒</strong>
</div>
<script type="text/javascript" src="common.js"></script>
<script type="text/javascript">
//计算时间差
function timeInterval(start, end) {
// 日期可以相减,内部调用了valueOf()方法
var interval = end - start;
var day = parseInt(interval/1000/60/60/24);
var hours = parseInt(interval/1000/60/60%24);
var minutes = parseInt(interval/1000/60%60);
var seconds = parseInt(interval/1000%60);
day = day < 10 ? '0'+day : day;
hours = hours < 10 ? '0'+hours : hours;
minutes = minutes < 10 ? '0'+minutes : minutes;
seconds = seconds < 10 ? '0'+seconds : seconds;
// console.log(day+'日'+hours+'时'+minutes+'分'+seconds+'秒')
return {
day:day,
hours:hours,
minutes:minutes,
seconds:seconds
}
}
倒计时
因为页面时间要不停的更新,所以需要用到闹钟定时器
var s1 = document.getElementById('s1');
var s2 = document.getElementById('s2');
var s3 = document.getElementById('s3');
var s4 = document.getElementById('s4');
var day,hours,minutes,seconds;//接收时间的变量
function fn() {
var currentTime = new Date(); //当前时间
var targetTime = new Date(2019,10,15); //目标时间
var d = timeInterval(currentTime, targetTime);
day = d.day;
hours = d.hours;
minutes = d.minutes;
console.log(minutes);
seconds = d.seconds;
s1.innerText = day;
s2.innerText = hours;
s3.innerText = minutes;
s4.innerText = seconds;
}
window.setInterval(fn, 1000);
fn();
</script>
</body>
</html>
网友评论