前言
计时功能在网页上是非常多的,现在我就用原生JS做个计时功能吧
HTML
<div><label>得到毫</label>
<h5></h5>
</div>
<div><label>得到秒</label>
<h4></h4>
</div>
<div><label>得到分</label>
<h3></h3>
</div>
<div><label>得到时</label>
<h2></h2>
</div>
<div><label>得到天</label>
<h1></h1>
</div>
JS
var StarTime = new Date().getTime();
setInterval(function() {
NotRetain();
}, 500)
function Retain() {
//保留小数点
var NowTime = new Date().getTime();
//毫
document.querySelectorAll("h5")[0].innerHTML = NowTime - StarTime + "毫秒";
//秒
document.querySelectorAll("h4")[0].innerHTML = (NowTime - StarTime) / 1000 + "秒"
//分
document.querySelectorAll("h3")[0].innerHTML = (NowTime - StarTime) / (1000 * 60) + "分"
//时
document.querySelectorAll("h2")[0].innerHTML = (NowTime - StarTime) / (1000 * 60 * 60) + "时"
//天
document.querySelectorAll("h1")[0].innerHTML = (NowTime - StarTime) / (1000 * 50 * 60 * 24) + "天"
}
function NotRetain() {
//不保留小数点
var NowTime = new Date().getTime();
//毫
document.querySelectorAll("h5")[0].innerHTML = NowTime - StarTime + "毫秒";
//秒
document.querySelectorAll("h4")[0].innerHTML = parseInt((NowTime - StarTime) / 1000) + "秒"
//分
document.querySelectorAll("h3")[0].innerHTML = parseInt((NowTime - StarTime) / (1000 * 60)) + "分"
//时
document.querySelectorAll("h2")[0].innerHTML = parseInt((NowTime - StarTime) / (1000 * 60 * 60)) + "时"
//天
document.querySelectorAll("h1")[0].innerHTML = parseInt((NowTime - StarTime) / (1000 * 50 * 60 * 24)) + "天"
}
效果
保留小数点
不保留小数点
完整代码
<html>
<head>
<meta charset="utf-8" />
<title>JS实现页面计时</title>
</head>
<body>
<div><label>得到毫</label>
<h5></h5>
</div>
<div><label>得到秒</label>
<h4></h4>
</div>
<div><label>得到分</label>
<h3></h3>
</div>
<div><label>得到时</label>
<h2></h2>
</div>
<div><label>得到天</label>
<h1></h1>
</div>
<script>
var StarTime = new Date().getTime();
setInterval(function() {
Retain();
}, 500)
function Retain() {
//保留小数点
var NowTime = new Date().getTime();
//毫
document.querySelectorAll("h5")[0].innerHTML = NowTime - StarTime + "毫秒";
//秒
document.querySelectorAll("h4")[0].innerHTML = (NowTime - StarTime) / 1000 + "秒"
//分
document.querySelectorAll("h3")[0].innerHTML = (NowTime - StarTime) / (1000 * 60) + "分"
//时
document.querySelectorAll("h2")[0].innerHTML = (NowTime - StarTime) / (1000 * 60 * 60) + "时"
//天
document.querySelectorAll("h1")[0].innerHTML = (NowTime - StarTime) / (1000 * 50 * 60 * 24) + "天"
}
function NotRetain() {
//不保留小数点
var NowTime = new Date().getTime();
//毫
document.querySelectorAll("h5")[0].innerHTML = NowTime - StarTime + "毫秒";
//秒
document.querySelectorAll("h4")[0].innerHTML = parseInt((NowTime - StarTime) / 1000) + "秒"
//分
document.querySelectorAll("h3")[0].innerHTML = parseInt((NowTime - StarTime) / (1000 * 60)) + "分"
//时
document.querySelectorAll("h2")[0].innerHTML = parseInt((NowTime - StarTime) / (1000 * 60 * 60)) + "时"
//天
document.querySelectorAll("h1")[0].innerHTML = parseInt((NowTime - StarTime) / (1000 * 50 * 60 * 24)) + "天"
}
</script>
</body>
</html>
后言
本文结束了,如果觉得本技术文章对你有帮助请给我点个赞,如果有什么不足的地方,给我提意见,让我加以改进