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

WordPress计数器动画:如何用WebKitMutationObserver替换小数点为逗号?

解决方案:用MutationObserver替换计数器小数点为逗号

直接用以下代码实现,把它添加到你的WordPress主题中(比如放在footer.php的</body>标签前,或者通过自定义HTML小工具插入):

document.addEventListener('DOMContentLoaded', function() {
  // 获取所有带counter类的元素
  const counters = document.querySelectorAll('.counter');
  
  counters.forEach(counter => {
    // 创建MutationObserver实例
    const observer = new MutationObserver(function(mutations) {
      mutations.forEach(mutation => {
        // 检测内容变化,且当前文本包含小数点
        if (mutation.type === 'childList' && counter.textContent.includes('.')) {
          // 替换小数点为逗号
          counter.textContent = counter.textContent.replace('.', ',');
          // 若计数器是一次性动画,替换完成后停止监听避免重复触发
          observer.disconnect();
        }
      });
    });

    // 配置监听规则:监听子节点变化(内容更新属于此范畴)
    const config = { childList: true };
    
    // 启动监听
    observer.observe(counter, config);
  });
});

补充说明:

如果你的计数器动画是循环执行的(比如会反复刷新数值),把代码里的observer.disconnect()替换成以下判断逻辑,防止无限触发替换:

if (mutation.type === 'childList' && counter.textContent.includes('.') && !counter.textContent.includes(',')) {
  counter.textContent = counter.textContent.replace('.', ',');
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 17:30:02