说明
原生js Date对象。replace兼容safari浏览器日期格式。
示例图
页面代码
<!-- author:韩涛 time:2021/11/3 -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="icon" href="https://upload.51yunmeng.com:9000/operation/BUSINESS_LICENSE/QQ图片20240206150247_1707202982530.png" type="image/x-icon" />
<title>Vacation</title>
<style>
*{padding:0;margin:0;}
html,body{
width:100%;height:100%;
overflow:hidden;
}
body{
background-size:100% 100%;
position:relative;
}
#box {
line-height: 50px;
text-align: center;
background-color: #000;
color: #fff;
font-size: 20px;
width:80%;
margin:40px auto;
border-radius:20px;
border:4px solid rgba(255, 255, 255, 0.5);
animation:move 5s linear infinite;
}
.cat{
width: 100%;
height: 100%;
position:absolute;
top:0;
left:0;
z-index: -1;
}
.copy{
position:absolute;
bottom: 10px;
left: 50%;
transform: translate(-50%,0);
font-style: italic;
color:#409EFF;
}
@keyframes move{ /* 炫酷旋转提示 */
0%{transform:rotateY(0deg);background: #409EFF;}
50%{transform: rotateY(90deg); background: green;}
100%{transform: rotateY(0deg);background: pink;}
}
/* 媒体查询:兼容手机端 */
@media screen and (max-width: 600px) { #box { background: #409EFF;/* width:300px; */}}
@media screen and (min-width: 650px) { #box { background: green;/* width:300px; */} }
@media screen and (min-width: 768px) { #box { background: blue;/* width:500px; */}}
@media screen and (min-width: 992px) { #box { background: orange;width:600px;} }
@media screen and (min-width: 1200px){ #box { background: pink;width:600px;}}
</style>
</head>
<body>
<div id="box">距XXXX/XX/XX余: xxx天xxx时xxx分xxx秒</div>
<div class="copy">©Author:hantao20211103</div>
<script>
//设置时间函数
function setTime() {
//创建未来日期
let timeStr = '2030-01-01 18:29:59'; // 这是结束时间点,自行修改。
let newDate = new Date((timeStr).replace(/-/g,'/')); // .replace(/-/g,'/')) 解决不兼容safari浏览器
//创建当前日期
let myDate = new Date();
let timeCha = newDate - myDate; //unit: ms //得到时间差
let day = Math.floor(timeCha / 1000 / 60 / 60 / 24); //剩余的天数
let hour = Math.floor(timeCha / 1000 / 60 / 60 % 24); //剩余小时
let minute = Math.floor(timeCha / 1000 / 60 % 60); //剩余的分钟
let second = Math.floor(timeCha / 1000 % 60); //剩余的秒数
let millisecond = Math.floor( timeCha%1000 ); //剩余毫秒
day = fillZero(day);
hour = fillZero(hour);
minute = fillZero(minute);
second = fillZero(second);
millisecond = fillSconedZero(millisecond);
// let box = document.querySelector("#box"); id可以不用获取,直接操作dom
if(timeCha>0){
box.innerHTML = `距${timeStr}余<br/> ${day}天${hour}时${minute}分${second}秒${ millisecond }毫秒`; // 拼接时间字符串,渲染到页面.
}
}
//补零
function fillZero(t) {
return t < 10 ? `0${t}` : t;
}
// 补毫秒
function fillSconedZero(t) {
if(t<10){
return `00${t}`;
}else if(t>=10 && t<=99){
return `0${t}`;
}else{
return t;
}
}
setTime(); //立即执行一次setTime函数
setInterval(setTime, 36); //计时器 = 每隔36毫秒调用一次setTime函数
</script>
</body>
</html>