码迷,mamicode.com
首页 > 其他好文 > 详细

DOM案例【1】文本时钟

时间:2018-01-14 12:10:06      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:rip   int   seconds   time   body   new   gettime   cal   inner   

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>

 

DOM案例【1】文本时钟

标签:rip   int   seconds   time   body   new   gettime   cal   inner   

原文地址:https://www.cnblogs.com/lolitagis02/p/8282412.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!