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

JS设置textContent并toggle类实现淡入仅隔次生效的问题求解

问题根因

你遇到的间隔触发淡入的问题由两个核心原因导致:

  • 你使用classList.toggle('fadein')切换类,初始状态下DOM元素已经带有fadein类,第一次点击会移除类无动画,第二次点击重新添加类才触发动画,因此出现每第二条名言才触发效果的问题
  • 直接重复添加同一个动画类,浏览器不会重新触发动画执行,需要先重置动画状态再添加类
修改方案

1. CSS调整

给淡入动画添加animation-fill-mode: forwards,保证动画结束后保持最终透明度状态,避免动画结束后元素闪烁:

.fadein {
  animation: fadeIn linear 7s;
  animation-fill-mode: forwards;
}

@keyframes fadeIn {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

2. JS逻辑调整

将所有classList.toggle('fadein')的逻辑替换为「先移除类→强制浏览器重绘重置动画→更新内容→重新添加类触发动画」的流程,修改后的完整JS代码如下:

const quotes = [
  ["quote 1", "author 1"],
  ["quote 2", "author 2"],
  ["quote 3", "author 3"],
  ["quote 4", "author 4"],
]
let quoteCount = 0;
let currentQuote = 0;
let quotesServed = [];

// 封装淡入触发逻辑,避免重复代码
function triggerFadeIn(heading, author) {
  // 先移除淡入类
  heading.classList.remove('fadein');
  author.classList.remove('fadein');
  // 读取offsetHeight强制浏览器重绘,重置动画状态
  void heading.offsetHeight;
  void author.offsetHeight;
  // 重新添加类触发动画
  heading.classList.add('fadein');
  author.classList.add('fadein');
}

function getQuote(event) {
  event.preventDefault(); // 阻止a标签默认跳转行为
  let nextQuote = 0;
  let randomQuote = 0;
  let prevQuote = 0;
  let elementHeading = document.getElementById('quoteheadingID');
  let elementAuthor = document.getElementById('quoteauthorID');
  const whichButton = event.target.classList.contains('next')? "next" : "previous";
  
  if (whichButton==="next") {
    if (quoteCount === quotesServed.length) {
      do {
        randomQuote = Math.floor(Math.random()*quotes.length);
      } while (randomQuote === quotesServed[quoteCount-1])

      elementHeading.textContent = quotes[randomQuote][0];
      elementAuthor.textContent = quotes[randomQuote][1];
      // 调用淡入触发方法
      triggerFadeIn(elementHeading, elementAuthor);

      quotesServed.push(randomQuote);
      quoteCount++;
    } else {
      if (quoteCount < quotes.length ) {
        nextQuote = quotesServed[quoteCount];
        elementHeading.textContent = quotes[nextQuote][0];
        elementAuthor.textContent = quotes[nextQuote][1];
        triggerFadeIn(elementHeading, elementAuthor);
        quoteCount++;
      } 
    }

  } else if (whichButton==="previous") {
    if (quoteCount > 1) {
      quoteCount--;
      prevQuote = quotesServed[quoteCount-1];
      elementHeading.textContent = quotes[prevQuote][0];
      elementAuthor.textContent = quotes[prevQuote][1];
      triggerFadeIn(elementHeading, elementAuthor);
    }
  }
}

document.querySelector('.next').addEventListener('click', getQuote);
document.querySelector('.previous').addEventListener('click', getQuote);

额外优化

新增了event.preventDefault()阻止a标签的默认跳转行为,避免点击按钮时页面跳转到顶部。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 04:06:03