如何为打字机轮播中data-rotate属性的轮播词设置不同背景色?
带匹配背景色的原生JS打字机轮播实现
原打字机轮播组件基于原生JS实现,通过DOM元素的data-rotate属性传入循环文本数组,内置逐字键入、逐字删除的自动循环逻辑。本次优化的核心目标是让每一段轮播文本匹配专属的对应背景色,具体实现步骤如下:
1. 调整DOM属性配置
为了保证文本和对应背景色的索引严格对齐,避免平行数组错位,将原本仅存纯文本数组的data-rotate属性值,调整为结构化的对象数组,每个对象包含待展示文本、对应背景色两个字段:
<!-- 优化后配置示例 --> <span class="typewriter" data-rotate='[ {"text":"前端开发", "bg":"#1e40af"}, {"text":"交互设计", "bg":"#047857"}, {"text":"性能优化", "bg":"#b45309"} ]' ></span>
2. 核心组件逻辑改造
在原有TxtRotate类的循环逻辑中,增加当前轮次的背景色读取与赋值逻辑,保证文本和背景色同步切换:
class TxtRotate { constructor(el, toRotate, period) { // 解析结构化的文本+配色配置 this.config = JSON.parse(toRotate); this.el = el; this.loopIndex = 0; this.holdPeriod = parseInt(period, 10) || 2000; this.currentTxt = ''; this.isDeleting = false; this.tick(); } tick() { // 获取当前循环轮次的配置 const currentConfig = this.config[this.loopIndex % this.config.length]; const fullText = currentConfig.text; // 新增:同步更新元素的背景色 this.el.style.backgroundColor = currentConfig.bg; // 原有逐字打/删逻辑 if (this.isDeleting) { this.currentTxt = fullText.substring(0, this.currentTxt.length - 1); } else { this.currentTxt = fullText.substring(0, this.currentTxt.length + 1); } this.el.innerHTML = `<span class="text-wrap">${this.currentTxt}</span>`; // 原有打字速度随机波动逻辑 let typingSpeed = 150 - Math.random() * 50; if (this.isDeleting) typingSpeed /= 2; // 原有状态切换逻辑 if (!this.isDeleting && this.currentTxt === fullText) { typingSpeed = this.holdPeriod; this.isDeleting = true; } else if (this.isDeleting && this.currentTxt === '') { this.isDeleting = false; this.loopIndex++; typingSpeed = 500; } setTimeout(() => this.tick(), typingSpeed); } } // 页面初始化加载组件 document.addEventListener('DOMContentLoaded', () => { document.querySelectorAll('.typewriter').forEach(el => { new TxtRotate(el, el.getAttribute('data-rotate'), el.getAttribute('data-period')); }); });
3. 配套样式优化
补充必要的样式,让颜色切换更平滑、打字效果更自然:
.typewriter { display: inline-block; padding: 3px 10px; border-radius: 6px; color: #fff; /* 背景色平滑过渡,避免硬切的突兀感 */ transition: background-color 0.3s ease; } .typewriter .text-wrap { border-right: 2px solid #fff; padding-right: 2px; /* 光标闪烁动画 */ animation: cursorBlink 0.7s step-end infinite; } @keyframes cursorBlink { 50% { border-color: transparent; } }
实现注意事项
- 写入
data-rotate属性的JSON结构需要严格符合语法要求,单双引号嵌套正确,避免解析报错 - 背景色与文本色需要保持足够的对比度,优先选择深色调背景搭配白色文本,保证可读性
- 如果不想改动原有纯文本数组的结构,也可以额外新增一个
data-rotate-bg属性存储平行的背景色数组,需要严格保证两个数组的长度、元素顺序完全一致,否则会出现颜色和文本错位的问题
内容的提问来源于stack exchange,提问作者Wilson
相关产品推荐
相关产品推荐

