效果图
    image.png

    1. <div>
    2. <div>
    3. 请输入到期时间:<input id="ipt" type="text" value="2022-07-29 17:56:00">
    4. <button>开始计时</button>
    5. </div>
    6. <div>
    7. 剩余时间:
    8. <span class="day">00天</span>
    9. <span class="hour">00小时</span>
    10. <span class="minute">00分钟</span>
    11. <span class="second">00秒</span>
    12. </div>
    13. </div>
    1. // 获取元素
    2. let day = document.querySelector('.day')
    3. let hour = document.querySelector('.hour');
    4. let minute = document.querySelector('.minute');
    5. let second = document.querySelector('.second');
    6. let btn = document.querySelector('button')
    7. let ipt = document.querySelector('input')
    8. btn.addEventListener('click', () => {
    9. console.log("输入框中的值为:", ipt.value)
    10. let iptVal = ipt.value
    11. // 设置到期时间
    12. let timing = new Date(iptVal)
    13. setInterval(() => {
    14. countDown(timing)
    15. }, 1000)
    16. })
    17. function countDown(time) {
    18. // 当前时间
    19. let nowTime = new Date()
    20. if (time < nowTime) {
    21. clearInterval(timer)
    22. return false
    23. }
    24. // 得到剩余时间 秒
    25. let timeRemaining = (time - nowTime) / 1000
    26. // 得到天数
    27. let d = Math.floor(timeRemaining / 60 / 60 / 24)
    28. d = d < 10 ? "0" + d : d
    29. day.innerHTML = d + "天"
    30. // 计算小时
    31. let h = Math.floor(timeRemaining / 60 / 60 % 24)
    32. h = h < 10 ? "0" + h : h
    33. // 追加到页面中
    34. hour.innerHTML = h + "小时"
    35. // 计算分钟
    36. let min = Math.floor(timeRemaining / 60 % 60)
    37. minute.innerHTML = min + "分"
    38. // 计算秒
    39. let sec = Math.floor(timeRemaining % 60)
    40. second.innerHTML = sec + "秒"
    41. }