本文实例为大家分享了vue实现电子时钟的具体代码,供大家参考,具体内容如下
html
<div class="dateBox">
<div class="time">{{ time }}</div>
<div class="date">{{ date }}</div>
</div>
css
.dateBox {
background: #121747;
background-image: url("~@/assets/images/时间.png");
background-repeat: no-repeat;
display: flex;
align-items: flex-end;
justify-content: flex-end;
position: absolute;
top: 70px;
right: 50px;
width: 400px;
height: 88px;
}
.date {
font-size: 28px;
color: #8ac9ff;
margin-left: 15px;
}
.time {
font-size: 48px;
color: #ffffff;
}
背景图片素材
js
以vue为例
data() {
return {
date: null,
time: null,
};
},
mounted() {
const clock = setInterval(() => {
this.date = getToday().date;
this.time = getToday().time;
}, 1000);
// 通过$once来监听定时器,在beforeDestroy钩子可以被清除。
this.$once("hook:beforeDestroy", () => {
clearInterval(clock);
});
},
// 日期时间格式化——获取当前日期时间,格式化为 2021/08/30 和 15:35:06
function getToday() {
var datas = new Date();
var on1 = "/";
var on2 = ":";
var onY = datas.getFullYear(); //年
var onM = datas.getMonth() + 1; //月
var onD = datas.getDate(); //日
var onS = datas.getHours(); //时
var onF = datas.getMinutes(); //分
var onN = datas.getSeconds(); //秒
if (onM >= 1 && onM <= 9) {
//月
onM = "0" + onM;
}
if (onD >= 1 && onD <= 9) {
//日
onD = "0" + onD;
}
if (onS >= 0 && onS <= 9) {
//时
onS = "0" + onS;
}
if (onF >= 0 && onF <= 9) {
//分
onF = "0" + onF;
}
if (onN >= 0 && onN <= 9) {
//秒
onN = "0" + onN;
}
return {
date: onY + on1 + onM + on1 + onD,
time: onS + on2 + onF + on2 + onN,
};
}