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

排查落地页每小时仅执行一次的CSS+JS动画代码错误

问题分析

原代码存在两个核心问题:

  1. 状态无法持久化:animationCompleted是内存变量,页面刷新或跳转后会被重置,导致每次加载都会重新执行动画,根本达不到“每小时仅执行一次”的要求。
  2. 逻辑错误:用setInterval等待一小时后才标记动画完成完全没必要——你的动画本身只有1秒时长,等一小时的操作毫无意义,反而会浪费资源。
修正方案

我们需要用localStorage来持久化存储最后一次执行动画的时间,每次页面加载时先对比当前时间与记录的时间,间隔超过1小时才触发动画。

修正后的完整代码:

HTML

<div class="text">
  <h1>NEN</h1>
</div>

CSS

.text {
  width: 100%;
  position: absolute;
  left: 50%;
  top: 45%;
  transform: translate(-50%, -50%);
  color: black;
  text-align: center;
  z-index: 1000;
  font-size: 0px;
}

@keyframes herot {
  0% {
    font-size: 16rem;
  }
  45% {
    font-size: 10rem;
  }
  50% {
    font-size: 10rem;
  }
  75% {
    font-size: 10rem;
  }
  90% {
    font-size: 10rem;
  }
  100% {
    font-size: 0px;
  }
}

注:原CSS重复定义了.text类,已合并避免冲突

JavaScript

function animateOncePerHour() {
  const STORAGE_KEY = 'lastAnimationTime';
  const ONE_HOUR = 60 * 60 * 1000;
  const lastTime = localStorage.getItem(STORAGE_KEY);
  const currentTime = Date.now();

  // 检查是否满足执行条件:无记录 或 距离上次执行超过1小时
  if (!lastTime || currentTime - parseInt(lastTime) > ONE_HOUR) {
    const textElement = document.querySelector('.text');
    // 触发动画
    textElement.style.animation = 'herot 1s';
    // 动画结束后重置样式(避免重复触发时样式冲突)
    textElement.addEventListener('animationend', () => {
      textElement.style.animation = 'none';
    }, { once: true });
    // 更新最后执行时间到localStorage
    localStorage.setItem(STORAGE_KEY, currentTime.toString());
  }
}

window.onload = animateOncePerHour;
关键改进点
  • 持久化存储:用localStorage记录最后一次动画执行的时间,页面刷新/跳转后依然能读取到状态。
  • 精准判断:通过时间差计算,严格控制每小时仅执行一次。
  • 优化资源:移除了无意义的setInterval,改用animationend事件处理动画结束后的样式重置,避免不必要的定时器消耗。

内容的提问来源于stack exchange,提问作者Thor The dog

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 14:10:26