You need to enable JavaScript to run this app. jQuery如何实现定时切换文本 支持循环播放与淡入淡出效果
优惠活动
大模型
产品
解决方案
定价
更多

jQuery如何实现定时切换文本 支持循环播放与淡入淡出效果

可直接运行的完整实现

核心调整逻辑

  • 原jQuery版本的无限循环缺口:消息数组被pop()取空时,重新从初始消息列表生成待读取的反转数组,即可自动回到第一条消息重新开始轮播,不需要打断原有动画流程
  • 原原生JS版本的淡入淡出效果:通过CSS原生过渡实现透明度变化,不需要引入jQuery,完全保留原有setTimeout的轮播时序

方案1:基于原有jQuery代码的优化

// 固定存储初始消息列表,避免被pop操作修改
const initialMsgList = [
    "Hello!",
    "This is a website!",
    "You are now going to be redirected.",
    "Are you ready?",
    "You're now being redirected..."
];

// 生成适配pop取数顺序的反转消息列表
let msgQueue = initialMsgList.slice().reverse();

function nextMsg() {
    if (msgQueue.length === 0) {
        // 队列取空时重新生成队列,自动开始下一轮循环
        msgQueue = initialMsgList.slice().reverse();
    }
    $('#message').html(msgQueue.pop()).fadeIn(500).delay(1000).fadeOut(500, nextMsg);
}

$('#message').hide();
nextMsg();

配套HTML(无需修改原有结构):

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<h1>Hello world!</h1>
<p>Here is a message: <span id="message"></span></p>
</body>
</html>

小提示:用slice()做数组拷贝再反转,是为了避免直接修改原始的消息列表,多次循环后出现顺序错乱的问题。

方案2:无jQuery依赖的原生实现(带淡入淡出)

先给轮播容器加基础样式,实现淡入淡出的动画效果:

#sequence {
    opacity: 0;
    transition: opacity 0.5s ease-in-out;
}
#sequence.active {
    opacity: 1;
}

修改原有原生JS的轮播逻辑,补全动画切换的时序:

const linkList = ['<a href="#"> link1</a>', '<a href="#"> link2</a>'];
const sequenceDom = document.getElementById("sequence");
// 单条消息静止展示时长
const displayTime = 5000;
// 动画时长和CSS里的transition值保持一致
const fadeTime = 500;

textSequence(0);
function textSequence(i) {
    if (linkList.length > i) {
        setTimeout(() => {
            // 先触发淡出动画
            sequenceDom.classList.remove('active');
            // 等淡出完成后,切换内容再淡入
            setTimeout(() => {
                sequenceDom.innerHTML = linkList[i];
                sequenceDom.classList.add('active');
                textSequence(++i);
            }, fadeTime);
        }, displayTime);
    } else if (linkList.length === i) {
        // 所有消息遍历完成后,从第一条重新开始循环
        textSequence(0);
    }
}

配套HTML结构:

<div id="sequence"></div>

效果细节:动画切换的节奏和原有轮播逻辑完全对齐,不会出现闪烁、时序错乱的问题,单条消息的展示时长、淡入淡出速度都可以通过变量直接调整。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.12 02:15:09