原生JS使用setInterval无jQuery实现多元素依次轮动切换样式效果
实现方案
第一步:添加高亮边框的CSS样式
先定义用于高亮的样式类,边框样式可按需自行调整:
.highlight-ad { border: 3px solid #ff4d4f; box-sizing: border-box; /* 避免加边框后区块尺寸变化 */ transition: border 0.2s ease; /* 可选,增加过渡效果更顺滑 */ }
第二步:修改JS代码,增加循环高亮逻辑
修改点说明:新增数组存储生成的所有广告区块,维护当前高亮索引,通过定时器每2秒切换高亮状态:
// 存储所有生成的广告区块 const adSections = []; // 记录当前高亮的区块索引 let currentHighlightIndex = 0; // 定时器实例,后续需要停止循环时可直接清除 let highlightTimer = null; function completeAd(obj) { const offers = obj['offers']; // 重新生成前清空旧内容和定时器,避免重复执行异常 adSection.innerHTML = ''; adSections.length = 0; if (highlightTimer) clearInterval(highlightTimer); for (let i = 0; i < 4; i++) { let rand = Math.floor((Math.random() * offers.length)); const singleAd = document.createElement('section'); singleAd.className = "adSection" const price = document.createElement('p'); const imgURL = document.createElement('img') imgURL.src = "http:" + offers[rand].imgURL price.textContent = offers[rand].price + " " + offers[rand].currency; singleAd.appendChild(price); singleAd.appendChild(imgURL); adSection.appendChild(singleAd); // 将生成的区块存入数组方便后续操作 adSections.push(singleAd); } // 区块生成完成后启动高亮循环 startHighlightLoop(); } function startHighlightLoop() { // 先给第一个区块添加初始高亮 adSections[currentHighlightIndex].classList.add('highlight-ad'); // 每2秒切换一次高亮 highlightTimer = setInterval(() => { // 移除当前区块的高亮 adSections[currentHighlightIndex].classList.remove('highlight-ad'); // 计算下一个索引,遍历到最后一个后自动回到开头 currentHighlightIndex = (currentHighlightIndex + 1) % adSections.length; // 给下一个区块添加高亮 adSections[currentHighlightIndex].classList.add('highlight-ad'); }, 2000) }
补充说明
- 若需要停止循环,直接执行
clearInterval(highlightTimer)即可 - 切换间隔可修改
setInterval的第二个参数调整,单位为毫秒 - 高亮样式可直接修改
.highlight-ad的CSS属性自定义
内容的提问来源于stack exchange,提问作者paciekFly
相关产品推荐
相关产品推荐

