HTML页面显示当前时间

1.在一个div里面显示当前时间

  用id选择器
<html>
<head>
    <meta charset="utf-8">
    <title>当前时间</title>
    <script type="text/javascript">
        var t = null;

        function time() {
            dt = new Date();
            var y = dt.getFullYear();
            var M = dt.getMonth() + 1;
            var d = dt.getDate();
            var h = dt.getHours();
            var m = dt.getMinutes();
            var s = dt.getSeconds();
            M=checkTime(M);
            d=checkTime(d);
       		h=checkTime(h);
            m=checkTime(m);
            s=checkTime(s);
            document.getElementById("timeShow").innerHTML = "当前时间:" + y + "-" + M + "-" + d + " " + h + ":" + m + ":" + s;
            t = setTimeout(time, 1000);
        }

        window.onload = function () {
            time()
        }
        
        function checkTime(i){
        if(i<10){
            i="0"+i;
        }
        return i;
    }
    </script>

</head>
<body>
<div id="timeShow"></div>
</body>
</html> 

显示结果:
在这里插入图片描述

2.如果多个div显示当前时间的话

   用class选择器
<html>
<head>
    <meta charset="utf-8">
    <title>当前时间</title>
    <script type="text/javascript">
        var t = null;

        function time() {
            dt = new Date();
            var y = dt.getFullYear();
            var M = dt.getMonth() + 1;
            var d = dt.getDate();
            var h = dt.getHours();
            var m = dt.getMinutes();
            var s = dt.getSeconds();
            M=checkTime(M);
    	    d=checkTime(d);
      		h=checkTime(h);
        	m=checkTime(m);
        	s=checkTime(s);
            $('.timeShow').html(y + "-" + M + "-" + d + " " + h + ":" + m + ":" + s);
            t = setTimeout(time, 1000);
        }

        window.onload = function () {
            time()
        }
        
    function checkTime(i){
        if(i<10){
            i="0"+i;
        }
        return i;
    }
    </script>

</head>
<body>
<div class="timeShow"></div>
<div class="timeShow"></div>
<div class="timeShow"></div>
</body>
</html>  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值