前端实现一个钟表功能

今日鸡汤

你人生一百次谨小慎微,你要有一次拍案而起; 人生一百次放浪形骸,要认真地爱一次; 人生一百次不越雷池一步,也要潇洒走一回! 一定要在人生的内存,给自己,给致爱的人,留一个百分之一空间,不随波逐流。


需求:前端需要实现一个钟表功能,实时展示当前时间。

思路:当页面加载时,获取一下系统时间。定义一个定时器,每一秒执行一次,将当前时间+1秒。

为了演示,这里的获取时间我直接在前端获取时间。

vue代码

<el-row :gutter="20">
<el-col :span="12">
<div id="content" class="grid-content bg-purple">
{{ currentYmd }} {{ currentHMS }}
</div>
</el-col>
</el-row>

js代码

export default {
 mounted() {
        this.timer = setInterval(() => {
            this.getCurrentTime();
        }, 1000);
    },
    beforeDestroy() {
        /* 离开页面前销毁定时器 */
        if (this.timer) {
            clearInterval(this.timer);
        }
    },
    data() {
        return {
            currentYmd"",
            currentHMS"",
            indexTime"",
        };
    },
    created() {
        this.indexTime = new Date(+new Date() + 8 * 3600 * 1000)
            .toJSON()
            .substr(019)
            .replace("T"" ");
    },
    methods: {
        getCurrentTime() {
            // 每次加1秒
            this.doAdd(this.indexTime, 1);
        },
        doAdd(date, num) {
            var d = new Date(
                date.substring(04),
                date.substring(57) - 1,
                date.substring(810),
                date.substring(1113),
                date.substring(1416),
                date.substring(1719)
            );
            d.setTime(d.getTime() + num * 1000);
            const currentTime =
                d.getFullYear() +
                "-" +
                this.checkTime(d.getMonth() + 1) +
                "-" +
                this.checkTime(d.getDate()) +
                " " +
                this.checkTime(d.getHours()) +
                ":" +
                this.checkTime(d.getMinutes()) +
                ":" +
                this.checkTime(d.getSeconds());
            this.indexTime = currentTime;
            this.currentYmd = currentTime.substring(010);
            this.currentHMS = currentTime.substring(1119);
        },
        checkTime(i) {
            if (i < 10) {
                i = "0" + i;
            }
            return i;
        },
}

页面效果

前端实现一个钟表功能


如果有更简单的实现方式,可以留言哦!



原文始发于微信公众号(ssw在路上的蚂蚁):前端实现一个钟表功能

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/89594.html

(0)
小半的头像小半

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!