1.给定一个时间,然后写出它和当前时间的倒计时(从毫秒开始转换)

  1. <p id="app">
  2. 00:00: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 23: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. console.log(gapTime);
  21. //4.毫秒和时分秒的转换
  22. var s = Math.floor(gapTime / 1000);
  23. var houer = handleTime(Math.floor(s / 3600));
  24. s = Math.floor(s % 3600);
  25. var minute = handleTime(Math.floor(s / 60));
  26. second = handleTime(Math.floor(s % 60));
  27. console.log(houer);
  28. console.log(minute);
  29. console.log(second);
  30. var sum = houer + ":" + minute + ":" + second;
  31. console.log(sum);
  32. app.innerHTML=sum;
  33. // setTimeout(function(){
  34. // showTime()
  35. // },1000)
  36. }
  37. //showTime();
  38. showTime();
  39. setInterval(function(){
  40. showTime();
  41. },1000)
  42. </script> //函数的两种写法

2.动态时钟

  1. <div>
  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 d = new Date();
  20. var hour = handleTime(d.getHours());
  21. var minute = handleTime(d.getMinutes());
  22. var second = handleTime(d.getSeconds());
  23. var imgs = document.querySelectorAll("img");
  24. var arr = hour + minute + second;
  25. // console.log(arr);
  26. //将图片的地址设置为动态
  27. for (i = 0; i < imgs.length; i++) {
  28. imgs[i] .src= "images/" + arr[i] + ".png"
  29. //imgs[i].src=`images/`${sum[i]}.png`;
  30. }
  31. setTimeout(function(){
  32. showTime()
  33. },1000)
  34. }
  35. showTime();
  36. </script>