1、处理时间

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

2、动态时钟

image.png

  1. <div id="box">
  2. <img src="images/0.png" alt="">
  3. <img src="images/0.png" alt="">
  4. <span class="colon">:</span>
  5. <img src="images/0.png" alt="">
  6. <img src="images/0.png" alt="">
  7. <span class="colon">:</span>
  8. <img src="images/0.png" alt="">
  9. <img src="images/0.png" alt="">
  10. </div>
  1. function handleTime(value){
  2. if(value<10){
  3. return "0"+value
  4. }else{
  5. return ""+value
  6. }
  7. }
  8. function showTime(){
  9. var imgs = document.querySelectorAll("#box img")
  10. var d = new Date()
  11. var hours = handleTime(d.getHours())
  12. var minutes = handleTime(d.getMinutes())
  13. var seconds = handleTime(d.getSeconds())
  14. var sum = hours+minutes+seconds
  15. // console.log(sum);
  16. // console.log(typeof sum);
  17. for(var i=0;i<imgs.length;i++){
  18. //imgs[i].src = "images/"+sum[i]+".png"
  19. // 字符串模板
  20. imgs[i].src = `images/${sum[i]}.png`
  21. }
  22. setTimeout(function(){
  23. showTime()
  24. },1000)
  25. }
  26. showTime()