example_of_js_4.html 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title>显示时间日期</title>
  6. <style>
  7. #clock {
  8. color: white;
  9. text-align: center;
  10. position: absolute;
  11. right: 10px;
  12. top: 10px;
  13. width: 280px;
  14. height: 40px;
  15. background-color: blue;
  16. font: 16px/40px "pt mono";
  17. }
  18. </style>
  19. </head>
  20. <body>
  21. <div id="clock"></div>
  22. <script>
  23. // JavaScript - 面向对象编程
  24. // 定义类创建对象
  25. const clockDiv = document.getElementById('clock')
  26. const weekdays = ['日', '一', '二', '三', '四', '五', '六']
  27. function showClock() {
  28. let now = new Date()
  29. let year = now.getFullYear()
  30. let mon = now.getMonth() + 1
  31. mon = mon < 10 ? '0' + mon : '' + mon
  32. let date = now.getDate()
  33. date = date < 10 ? '0' + date : '' + date
  34. let hour = now.getHours()
  35. hour = hour < 10 ? '0' + hour : '' + hour
  36. let min = now.getMinutes()
  37. min = min < 10 ? '0' + min : '' + min
  38. let sec = now.getSeconds()
  39. sec = sec < 10 ? '0' + sec : '' + sec
  40. let day = now.getDay()
  41. let fullStr = `${year}年${mon}月${date}日
  42. ${hour}:${min}:${sec} 星期${weekdays[day]}`
  43. clockDiv.textContent = fullStr
  44. }
  45. showClock()
  46. setInterval(showClock, 1000)
  47. // var timerId = setInterval(showClock, 1000)
  48. // clearInterval(timerId)
  49. </script>
  50. </body>
  51. </html>