前言
我们平时在闲逛一些网站的时候,会发现很多网站底部都记录了当前网站
记录了当前站点运行了多长时间,当用户看到时,会增强用户的信任感
网站运营的时间越长,也就意味着网站越稳定,越值得信赖
原生JS实现
代码语言:javascript复制<span id="runtime_span" style="color: #9b51e0;font-weight:bold"></span>
<script type="text/javascript">
function show_runtime(){
window.setTimeout("show_runtime()",1000);
X = new Date("01/06/2016 5:22:00");
Y = new Date();
T = (Y.getTime()-X.getTime());
M = 24*60*60*1000;
a = T/M;
A = Math.floor(a);
b = (a-A)*24;
B = Math.floor(b);
c = (b-B)*60;
C = Math.floor((b-B)*60);
D = Math.floor((c-C)*60);
runtime_span.innerHTML="本站已经稳定运行: " A "天" B "小时" C "分" D "秒"
}
show_runtime();
</script>
核心的原理就是,获取当前的时间减去设置初始时的时间,将时间转化成年,天,小时,分,秒,然后通过js
中的innerHTML
DOM属性将内容插入到页面中
Vue版本实现
代码语言:javascript复制<template>
<div class="add-website-long-time">
<span>{{runTimeText}}</span>
</div>
</template>
<script>
export default {
name: 'addLongTime',
data() {
return {
runTimeText: '',
}
},
mounted() {
this.timer = setInterval(this.runTime,1000);
},
methods: {
runTime() {
let X = new Date("01/06/2020 5:22:00"); // 设置的初始时间
let Y = new Date(); // 当前时间
let T = (Y.getTime()-X.getTime());
let M =24*60*60*1000;
let a = T/M;
let A = Math.floor(a);
let b = (a-A)*24;
let B = Math.floor(b);
let c = (b-B)*60;
let C = Math.floor((b-B)*60);
let D = Math.floor((c-C)*60);
this.runTimeText = "本站已经稳定运行: " A "天" B "小时" C "分" D "秒"
}
},
beforeDestroy() {
clearInterval(this.timer)
}
}
</script>
<style>
.add-website-long-time {
text-align: center;
}
</style>
</script>
只要会原生JS
,那么写Vue版本或React都是语法上差异,核心的逻辑依旧是没有变的