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

如何通过JavaScript实现文本按每20词分段显示、隐藏剩余内容且循环轮播

文本按词组分段循环轮播实现方案

以下是原生HTML/CSS/JS实现方案,无第三方依赖,所有参数可自行调整:

核心可配置项

  • 每组显示词数:支持在20-25区间自定义
  • 切换间隔时长:可根据阅读速度调整

完整实现代码

HTML 部分

<!-- 原始文本容器,加载后自动隐藏 -->
<p id="source-text">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Egestas integer eget aliquet nibh praesent. Rhoncus aenean vel elit scelerisque. Proin sed libero enim sed.</p>
<!-- 轮播内容展示容器 -->
<h2 id="text-carousel"></h2>

CSS 部分(可选,用于优化展示效果)

#source-text {
  display: none;
}
#text-carousel {
  transition: opacity 0.3s ease;
}

JavaScript 部分

// 自定义配置
const WORDS_PER_GROUP = 22; // 每组词数,可在20-25区间修改
const SWITCH_INTERVAL = 2500; // 每组内容停留时长,单位为毫秒

// 处理原始文本分词、分组
const sourceText = document.getElementById('source-text').textContent.trim();
const words = sourceText.split(/\s+/);
const wordGroups = [];
for (let i = 0; i < words.length; i += WORDS_PER_GROUP) {
  wordGroups.push(words.slice(i, i + WORDS_PER_GROUP).join(' '));
}

// 轮播逻辑
const carouselEl = document.getElementById('text-carousel');
let currentIndex = 0;
function switchGroup() {
  // 如需开启淡入淡出效果,可取消下方注释
  // carouselEl.style.opacity = 0;
  // setTimeout(() => {
    carouselEl.textContent = wordGroups[currentIndex];
    currentIndex = (currentIndex + 1) % wordGroups.length;
    // carouselEl.style.opacity = 1;
  // }, 200);
}

// 启动轮播
switchGroup();
setInterval(switchGroup, SWITCH_INTERVAL);

使用说明

直接将代码复制到页面对应位置即可运行,调整开头的配置参数即可匹配你的实际需求,最后一组不足指定词数时会自动正常展示剩余内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.15 14:36:04