DOM案例【1】文本时钟

1.网络参考

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <title></title>
</head>
<body>
    <p id="timer">时间显示</p>
</body>
</html>
<script language="javascript" type="text/javascript">
    //间隔计时器或者单次计时器
    window.onload = function () {
        setInterval(showtime, 10);
    }
    //补全分秒的个位数
    function checktime(time) {
        if (time < 10)
            time = '0' + time;
        return time;
    }
    function showtime() {
        //输出星期需要转换显示格式
        var weeks = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
        var mytime = new Date(),
                timer = document.getElementById("timer");
        //JS月份从0起算,需要加一
        var mon = mytime.getMonth() + 1;
        var hou = checktime(mytime.getHours()),
                min = checktime(mytime.getMinutes()),
                sec = checktime(mytime.getSeconds());
        timer.innerHTML = mytime.getFullYear() + "" + mon + "" + mytime.getDate() + "日 " +
                weeks[mytime.getDay()] + " " +
                hou + ":" + min + ":" + sec;
        //setTimeout(showtime,10);
    }
</script>

2.个人实现

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <div id="timer"></div>
</body>
</html>
<script type="text/javascript">
    //检查时间,补零
    function checkTime(time) {
        if (time < 10) {
            time = "0" + time;
        }
        return time;
    }
    //获取当前时间
    function getTimeString() {
        var date = new Date();
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        if (month < 10) {
            month = "0" + month;
        }
        var day = checkTime(date.getDate());
        var hour = checkTime(date.getHours());
        var minute = checkTime(date.getMinutes());
        var second = checkTime(date.getSeconds());

        var timeString = year + "-" + month + "-" + day + "  " + hour + ":" + minute + ":" + second;
        return timeString;
    }

    setInterval(function () {
        var res = getTimeString();
        document.getElementById("timer").innerHTML = res;
    }, 1000);
</script>

 

posted @ 2018-01-14 10:10  LolitaGIS的笔记  阅读(194)  评论(0编辑  收藏  举报