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. /* 间歇调用 */
  35. setInterval(function(){
  36. showTime()
  37. },1000)
  38. </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>
function handleTime(value){
  if(value<10){
    return "0"+value
  }else{
    return ""+value
  }
}
function showTime(){
  var imgs = document.querySelectorAll("#box img")
  var d = new Date()
  var hours = handleTime(d.getHours())
  var minutes = handleTime(d.getMinutes())
  var seconds = handleTime(d.getSeconds())
  var sum = hours+minutes+seconds
  // console.log(sum);
  // console.log(typeof sum);
  for(var i=0;i<imgs.length;i++){
    //imgs[i].src = "images/"+sum[i]+".png"
    // 字符串模板
    imgs[i].src = `images/${sum[i]}.png`
  }
  setTimeout(function(){
    showTime()
  },1000)
}
showTime()