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

JavaScript+PHP倒计时多场景显示逻辑调整求助

修正倒计时逻辑错误的解决方案

原代码核心问题

  1. 第一个条件判断distance >= 86400000 && distance < 21600000逻辑矛盾:24小时(86400000毫秒)远大于6小时(21600000毫秒),该条件永远无法触发
  2. 剩余时长小于0时未按需求显示"Closed",错误输出了error文本

修正后的完整代码

$(".expiry").each(function() {
    var expiry = new Date($(this).text());
    var selector = $(this);
    var x = setInterval(function() {
        var currentDateObj = new Date();
        var numberOfMlSeconds = currentDateObj.getTime();
        var addMlSeconds = 60 * 60 * 1000;
        var now = new Date(numberOfMlSeconds - addMlSeconds);

        var distance = expiry - now;
        var days = Math.floor(distance / (1000 * 60 * 60 * 24));
        var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        var seconds = Math.floor((distance % (1000 * 60)) / 1000);

        // 修正后的条件判断逻辑
        if (distance > 86400000) {
            // 剩余时长超过24小时,显示目标日期
            selector.next(".countdown").html(expiry);
        } else if (distance <= 21600000 && distance > 0) {
            // 剩余时长6小时及以内且未到期,显示时分秒倒计时
            selector.next(".countdown").html(`${days}d ${hours}h ${minutes}m ${seconds}s `);
        } else if (distance <= 0) {
            // 已到期,显示Closed
            selector.next(".countdown").html('<p>Closed</p>');
        }
    }, 1000);
});

关键修正说明

  • 调整第一个条件为distance > 86400000,匹配"剩余时长超过24小时"的需求
  • 新增distance <= 0分支,明确触发"Closed"显示逻辑
  • 用模板字符串优化倒计时文本拼接,提升代码可读性
  • 补全变量声明后的分号,修复语法细节问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 08:20:32