如何使用window.setInterval制作时钟

今天参考网上的一些case学习了一下动态时钟的写法,先看看html和JS怎么写:

这里的函数还是比较简单的,主要是通过window.setInterval(changeClock, 1000);没秒调用一次changeClock,然后再通过innerHTML方法跟新页面显示。这里有一个问题,就是为什么月份要加1?

<script>
	function changeClock()
	{
		var date = new Date();
		this.month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1 ) : (date.getMonth() + 1 );
		this.date = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
		this.hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
		this.minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
		this.second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();

		document.getElementById("clock").innerHTML = date.getFullYear() + "-" + this.month + "-" + this.date + " " + this.hour + ":" + this.minute + ":" + this.second;
	}
	window.setInterval(changeClock, 1000);
</script>

html当然也很简单:

<html>
      	<head>
	</head> 
	<body> 
		<div id="clock" style="float:right"></div> 
	</body>
</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值