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

jQuery 如何为setTimeout触发的文本切换添加淡入淡出过渡效果

实现文本切换淡入淡出效果的方案

方案1:使用jQuery内置淡入淡出方法(最简实现)

直接利用jQuery提供的fadeOut()、fadeIn()方法控制文本容器的显隐过渡,修改后的代码如下:

let timer = 0;
// 动画时长,单位毫秒,可自行调整
const animationDuration = 500;
// 切换间隔5秒,扣除两次动画时长避免总等待时间叠加
const switchInterval = 5000 - animationDuration * 2;

do_test(timer);

function do_test(timer){
  timer++;
  // 先执行淡出动画
  $('#cnt').fadeOut(animationDuration, () => {
    // 淡出完成后修改文本和背景色
    if (timer > 29){
      $('body').css('background','blue');
    }else if (timer > 20){
      $('body').css('background','green');
    }else if (timer > 10){
      $('body').css('background','pink');
    }else if (timer > 3){
      $('body').css('background','yellow');
    }
    $('#cnt').text(timer);
    // 再执行淡入动画
    $('#cnt').fadeIn(animationDuration, () => {
      if (timer < 40){
        // 淡入完成后等待指定间隔再执行下一次切换
        setTimeout(() => {do_test(timer)}, switchInterval);
      } else {
        $('body').html('<div id="dun">DONE</div>');
      }
    })
  })
}

原有HTML代码无需修改:

<div id="cnt"></div>

方案2:CSS过渡实现(性能更优)

通过CSS控制过渡效果,渲染性能更稳定,需要先新增对应样式:

#cnt {
  transition: opacity 0.5s ease;
}
.hide {
  opacity: 0;
}
/* 如果需要背景色也带过渡效果,可新增以下样式 */
body {
  transition: background 0.5s ease;
}

修改后的JS代码:

let timer = 0;
const animationDuration = 500;
const switchInterval = 5000;

do_test(timer);

function do_test(timer){
  timer++;
  const $cnt = $('#cnt');
  // 添加隐藏类触发淡出过渡
  $cnt.addClass('hide');
  // 等待过渡完成后修改内容
  setTimeout(() => {
    if (timer > 29){
      $('body').css('background','blue');
    }else if (timer > 20){
      $('body').css('background','green');
    }else if (timer > 10){
      $('body').css('background','pink');
    }else if (timer > 3){
      $('body').css('background','yellow');
    }
    $cnt.text(timer);
    // 移除隐藏类触发淡入过渡
    $cnt.removeClass('hide');

    if (timer < 40){
      setTimeout(() => {do_test(timer)}, switchInterval);
    } else {
      $('body').html('<div id="dun">DONE</div>');
    }
  }, animationDuration)
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 15:06:05