vue -电子时钟

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript" src="js/vue.js"></script>
</head>
<body>

<div id="clock">
    <h1>Gary</h1>
    <p class="date">{{ date }}</p>
    <p class="time">{{ time }}</p>
    <p class="text">数字时钟</p>
</div>

</body>
<script>
    var clock = new Vue({
        el: '#clock',
        data: {
            time: '',
            date: ''
        }
    });

    var week = ['星期天', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
    var timerID = setInterval(updateTime, 1000);
    updateTime();
    function updateTime() {
        var cd = new Date();
        clock.time = week[cd.getDay()];
        clock.date = zeroPadding(cd.getFullYear(), 4) + '-' + zeroPadding(cd.getMonth()+1, 2) + '-' + zeroPadding(cd.getDate(), 2) + ' '+zeroPadding(cd.getHours(), 2) + ':' + zeroPadding(cd.getMinutes(), 2) + ':' + zeroPadding(cd.getSeconds(), 2);
    };

    function zeroPadding(num, digit) {
        var zero = '';
        for(var i = 0; i < digit; i++) {
            zero += '0';
        }
        return (zero + num).slice(-digit);
    }

</script>
</html>

说明:

setInterval(code,millisec) :可按照指定的周期(以毫秒计)来调用函数或计算表达式

  code:要调用的函数或要执行的代码串

  millisec :周期性执行或调用 code 之间的时间间隔,以毫秒计

复制代码
function zeroPadding(num, digit) {
    var zero = '';
    for(var i = 0; i < digit; i++) {
        zero += '0';
    }
    return (zero + num).slice(-digit);
}
复制代码

num参数:返回系统时间

dight参数:当时钟小于两位数digit位数时候补,年份四位,月日为两位

js.slice() 方法可从已有的数组中返回选定的元素


updateTime()函数中调用zeroPadding()统一数字时钟时间格式

function updateTime() {
    var cd = new Date();
    clock.time = zeroPadding(cd.getHours(), 2) + ':' + zeroPadding(cd.getMinutes(), 2) + ':' + zeroPadding(cd.getSeconds(), 2);
    clock.date = zeroPadding(cd.getFullYear(), 4) + '-' + zeroPadding(cd.getMonth()+1, 2) + '-' + zeroPadding(cd.getDate(), 2) + ' ' + week[cd.getDay()];
};

JavaScript Date 对象:

getHours() :返回 Date 对象的小时 (0 ~ 23)
getMinutes() :返回 Date 对象的分钟 (0 ~ 59)
getSeconds() :返回 Date 对象的秒数 (0 ~ 59)
setFullYear() :设置 Date 对象中的年份(四位数字)
getMonth() :从Date 对象返回月份 (0 ~ 11)
getDate() :从Date 对象返回一个月中的某一天 (1 ~ 31)

转载=https://www.cnblogs.com/1138720556Gary/p/9381643.html

猜你喜欢

转载自www.cnblogs.com/dk2557/p/11357815.html