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

如何通过回调实现计数为0时触发div元素闪烁

解决方案

直接上修改后的完整代码,再逐个拆解关键改动:

完整代码

HTML

<h1>callback</h1><br />
<div id="count">3</div><br />
<button id="btn">点击触发闪烁</button>

CSS

*,
*::after,
*::before {
  padding: 0px;
  margin: 0px;
  font-family: inherit;
}

html,
body {
  height: 100vh;
}

body {
  font-family: sans-serif;
  font-size: 16px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: aliceblue;
}

#count {
  font-size: 3rem;
  background-color: #4c96af;
  padding: 2px 12px;
  margin-left: 16px;
  margin-right: 16px;
  border-radius: 4px;
  color: #fff;
}

button {
  position: relative;
  background-color: #4caf50;
  border: none;
  font-size: 28px;
  color: #ffffff;
  padding: 15px;
  width: 150px;
  text-align: center;
  transition-duration: 0.4s;
  text-decoration: none;
  overflow: hidden;
  cursor: pointer;
  border-radius: 3px;
}

button:after {
  content: "";
  background: #f1f1f1;
  display: block;
  position: absolute;
  padding-top: 300%;
  padding-left: 350%;
  margin-left: -20px !important;
  margin-top: -120%;
  opacity: 0;
  transition: all 0.8s;
}

button:active:after {
  padding: 0;
  margin: 0;
  opacity: 1;
  transition: 0s;
}

.blink-bg {
  animation: blinkingBackground 0.5s ease-in-out 3; /* 调整动画参数,让闪烁更明显 */
}

@keyframes blinkingBackground {
  50% {
    background-color: #ef0a1a;
  }
}

JavaScript

// 提前缓存DOM元素,避免重复查询浪费性能
const countEl = document.querySelector("#count");
const btn = document.querySelector("#btn");

// 把闪烁功能封装成独立函数,方便多处调用
function triggerBlink() {
  // 添加闪烁类触发动画
  countEl.classList.add("blink-bg");
  // 动画结束后自动移除类,确保下次触发能重新生效
  countEl.addEventListener("animationend", function removeClass() {
    countEl.classList.remove("blink-bg");
    countEl.removeEventListener("animationend", removeClass);
  });
}

// 倒计时逻辑
setInterval(function() {
  let result = Number(countEl.innerText) - 1;

  if (result < 0) {
    result = 3;
  }

  countEl.innerText = result;

  // 当数值变为0时,调用闪烁函数
  if (result === 0) {
    triggerBlink();
  }
}, 1000);

// 按钮点击时触发闪烁
btn.addEventListener("click", triggerBlink);

关键改动说明

  • 封装闪烁函数:把闪烁逻辑抽成triggerBlink独立函数,不管是倒计时到0还是按钮点击,直接调用这个函数即可。用animationend事件确保动画结束后移除类,避免重复添加导致动画失效。
  • 缓存DOM元素:提前查询并缓存#count和#btn元素,避免每次定时器执行都重复查询DOM,提升运行效率。
  • 倒计时触发闪烁:在更新完数值后,判断如果结果为0,立即调用闪烁函数。
  • 优化CSS动画:调整了.blink-bg的动画时长和重复次数,把原来的100ms改成0.5秒、重复3次,让闪烁效果更易察觉。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 14:01:05