1.倒计时

  1. <p id="app">
  2. 10:10:00
  3. </p>
  4. <script>
  5. function handleTime(value) {
  6. if (value < 10) {
  7. return "0" + value;
  8. }
  9. return "" + value;
  10. }
  11. function showTime() {
  12. var app = document.getElementById("app")
  13. var endTime = "2020-12-01 16:50:00";
  14. /* 1.获取结束时间的毫秒 */;
  15. endTime = new Date(endTime).getTime();
  16. /* 2.获取当前时间的毫秒 */
  17. var nowTime = new Date().getTime();
  18. /* 3.获取他们之间的差 */
  19. var gapTime = endTime - nowTime;
  20. /* 4.将他们的差转换为时分秒 */
  21. var seconds = Math.floor(gapTime / 1000);
  22. var hours = handleTime(Math.floor(seconds / 3600));
  23. seconds = seconds % 3600;
  24. var minutes = handleTime(Math.floor(seconds / 60));
  25. seconds = handleTime(seconds % 60);
  26. var sum = hours + ":" + minutes + ":" + seconds;
  27. app.innerHTML = sum;
  28. }
  29. showTime();
  30. setInterval(function(){
  31. showTime();

2.动态时钟

  1. <div id="app">
  2. <img src="images/0.png" alt="">
  3. <img src="images/0.png" alt="">
  4. <span>:</span>
  5. <img src="images/0.png" alt="">
  6. <img src="images/0.png" alt="">
  7. <span>:</span>
  8. <img src="images/0.png" alt="">
  9. <img src="images/0.png" alt="">
  10. </div>
  11. <script>
  12. function handleTime(value) {
  13. if (value < 10) {
  14. return "0" + value;
  15. }
  16. return "" + value;
  17. }
  18. function showTime() {
  19. var imgs = document.querySelectorAll("#app img")
  20. var d = new Date();
  21. var hours = handleTime(d.getHours());
  22. var minutes = handleTime(d.getMinutes());
  23. var seconds = handleTime(d.getSeconds());
  24. var sum = hours + minutes + seconds;
  25. for (var i = 0; i < imgs.length; i++) {
  26. // imgs[i].src = "images/" + sum[i] + ".png";
  27. imgs[i].src = `images/${sum[i]}.png`;
  28. }
  29. setTimeout(function(){
  30. showTime()
  31. },1000)
  32. }
  33. showTime()
  34. </script>