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

如何使用JS精准定位HTML中指定的span标签实现淡入淡出效果

解决方法

只需要修改querySelectorAll的选择器参数,将全局匹配所有span改为仅匹配类名为animated的容器下的span即可:

// 仅选中.animated容器内的所有span标签
const spans = document.querySelectorAll(".animated span");
const animation = function () {
  for (let span of spans) span.classList.toggle("fade");
};
setInterval(animation, 2400);

可选更精准方案

如果后续你在animated容器内可能新增其他不需要动画的span标签,可以直接指定目标span的id来匹配,完全避免误选:

// 直接通过id选中两个目标span,精准度更高
const spans = document.querySelectorAll("#animated-name, #animated-text");
const animation = function () {
  for (let span of spans) span.classList.toggle("fade");
};
setInterval(animation, 2400);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 07:45:03