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

JavaScript setProperty仅对首个DaisyUI倒计时器生效,求解决方案

问题分析与解决方法

你的问题核心有两个:

  • 所有倒计时器共用了同一个目标日期
  • 定时器更新时只会修改页面中第一个匹配的.timer-hours/.timer-minutes/.timer-seconds元素

具体错误点:

  1. 日期获取逻辑错误:
    你在循环外只获取了第一个.timer-counter对应的.timer-item的data-counter-date,导致所有倒计时器都用同一个时间值,而非各自独立的目标时间。
  2. 元素选择范围错误:
    document.querySelector('.timer-hours')只会返回页面中第一个匹配该类名的元素,所以无论多少个定时器,只有第一个会被更新。
  3. 参数传递错误:
    startTimer接收的第一个参数是循环索引key,而非当前倒计时器的DOM元素,无法定位到当前定时器的子元素。

修正后的代码:

JavaScript 代码:

let timerCounters = jQuery('.timer-counter');
// 检查是否存在倒计时器元素
if (timerCounters.length > 0) {
    timerCounters.each(function(index, element) {
        // 获取当前倒计时器对应的目标日期
        const $timerItem = jQuery(element).closest('div').find('.timer-item');
        const datetime = $timerItem.attr('data-counter-date');
        if (!datetime) return;
        // 传入当前元素和对应日期启动定时器
        startTimer(element, datetime);
    });
}

function startTimer(timerElement, countDown) {
    const countDownDate = new Date(countDown).getTime();
    const $timer = jQuery(timerElement);
    // 定位当前定时器内的时间显示元素
    const $hours = $timer.find('.timer-hours');
    const $minutes = $timer.find('.timer-minutes');
    const $seconds = $timer.find('.timer-seconds');

    const interval = setInterval(function() {
        const now = new Date().getTime();
        const distance = countDownDate - now;

        const days = Math.floor(distance / (1000 * 60 * 60 * 24));
        const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        const seconds = Math.floor((distance % (1000 * 60)) / 1000);

        // 更新当前定时器的CSS变量
        $hours.get(0).style.setProperty('--value', hours);
        $minutes.get(0).style.setProperty('--value', minutes);
        $seconds.get(0).style.setProperty('--value', seconds);

        if (distance <= 0) {
            clearInterval(interval);
            // 若不需要全局刷新,可替换为单个定时器的结束逻辑
            // location.reload();
        }
    }, 1000);
}

补充说明:

  • 使用jQuery.each遍历每个倒计时器,确保每个定时器获取自己的目标日期
  • 将当前倒计时器的DOM元素传入startTimer,通过元素范围查找对应的时间显示节点,避免全局选择
  • 移除了不必要的location.reload()(若业务需要全局刷新可保留,但多个定时器时会导致一个结束就刷新页面)

额外检查:

确保你的HTML结构中,每个.timer-counter确实包裹了对应的.timer-item,否则closest('div').find('.timer-item')可能无法正确定位目标元素。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 09:10:26