页面电子时钟
页面电子时钟
要求
页面上有一个电子时钟,显示当前的年月日时分秒,要求自动变化。
思路
1、开启定时器,每隔1秒执行1次回调函数
2、回调函数中,使用Date对象获取当前时分秒
3、判断时分秒是否大于10
4、将时分秒内容拼接成字符串,并设置盒子的内容
<body><div class="electronicClock"></div><script>var electronicClock = document.querySelector('.electronicClock');getTime(); // 先调用一次setInterval(getTime, 1000);function getTime() {var time = new Date();var year = time.getFullYear();var month = time.getMonth() + 1;month = month < 10 ? '0' + month : month;var date = time.getDate();date = date < 10 ? '0' + date : date;var day = time.getDay();var week = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六']var hours = time.getHours();hours = hours < 10 ? '0' + hours : hours;var minutes = time.getMinutes();minutes = minutes < 10 ? '0' + minutes : minutes;var seconds = time.getSeconds();seconds = seconds < 10 ? '0' + seconds : seconds;var str = year + '年' + month + '月' + date + '日 ' + week[day] + ' ' + hours + '时' + minutes + '分' + seconds + '秒';electronicClock.innerHTML = str;}</script>
</body>