You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

倒计时代码片段:实现天数、小时数小于1时隐藏对应值

实现方案

你可以通过先计算各时间单位的数值,再判断数值大小控制对应DOM元素的显隐即可,修改后的代码如下:

<script type="text/javascript">
  var second = 1000,
      minute = second * 60,
      hour = minute * 60,
      day = hour * 24;
  var countDown = new Date('{{- end_date -}}').getTime(),
      x = setInterval(function() {
      var now = new Date().getTime(),
          distance = countDown - now;
      
      // 倒计时结束逻辑,可根据需求调整
      if (distance < 0) {
        clearInterval(x)
        // 可自定义结束后的展示逻辑,比如显示"已结束"
        return
      }

      // 先计算各时间单位数值
      const days = Math.floor(distance / (day))
      const hours = Math.floor((distance % (day)) / (hour))
      const minutes = Math.floor((distance % (hour)) / (minute))
      const seconds = Math.floor((distance % (minute)) / second)

      // 控制天数字段显隐
      const dayDom = document.querySelector('.js-timer-days')
      if (days >= 1) {
        dayDom.innerText = days
        dayDom.style.display = 'inline' // 取值和元素原有显示属性对齐即可,比如inline-block、block
      } else {
        dayDom.style.display = 'none'
      }

      // 控制小时字段显隐
      const hourDom = document.querySelector('.js-timer-hours')
      if (hours >= 1) {
        hourDom.innerText = hours
        hourDom.style.display = 'inline'
      } else {
        hourDom.style.display = 'none'
      }

      // 分钟、秒默认保留,需要隐藏可按照上面的逻辑加判断
      document.querySelector('.js-timer-minutes').innerText = minutes
      document.querySelector('.js-timer-seconds').innerText = seconds
    }, second)
</script>

代码说明

  • 先单独计算各时间单位的数值,避免重复计算
  • 对天数、小时分别做数值判断:数值≥1时赋值并显示元素,数值小于1时直接隐藏对应元素,不会出现0天、0小时的无效展示
  • 如果需要同时隐藏小于1的分钟或秒,按照相同逻辑加判断即可
  • style.display的取值要和页面对应元素的原有显示属性保持一致,避免样式错乱

内容的提问来源于stack exchange,提问作者Quanto

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 18:06:02