我有一个如下所示的DOM,其中只有在第三个锚元素(仅 4th 和 5th 元素)之后才能添加/删除类
<div class="featured-block">
<a href="" class="featured-block__item cf"> <!-- 1st element -->
</a>
<a href="" class="featured-block__item cf"> <!-- 2nd element -->
</a>
<a href="" class="featured-block__item cf"> <!-- 3rd element -->
</a>
<a href="" class="featured-block__item cf"> <!-- Add/remove (4th element)-->
</a>
<a href="" class="featured-block__item cf"> <!-- Add/remove (5th element)-->
</a>
</div>
我已使用以下 JS代码,以便在第4 个以上DOM中添加/删除类features-block__item-active 和第五名。
我现在遇到的问题是 它在第4 和 5 位置上添加/删除班级,然后在上再次添加/删除班级>第一/第二/第三位置(我不想要)。
document.querySelectorAll('.featured-block .featured-block__item')[3].classList.add('featured-block__item-active'); // Line Z (Adding at 4th element)
const pics = document.querySelectorAll('.featured-block .featured-block__item');
function toggleClass() {
const activePic = document.querySelector('.featured-block__item.featured-block__item-active');
const activeIndex = Array.prototype.indexOf.call(pics, activePic);
const nextIndex = activeIndex === lastPic ? 0 : activeIndex + 1;
const nextPic = pics[nextIndex];
setTimeout(() => activePic.classList.remove('featured-block__item-active'), transitionDelay); // Line A
setTimeout(() => nextPic.classList.add('featured-block__item-active'), totalDelay); // Line B
}
setInterval(toggleClass, intervalDelay);
问题陈述:
我想知道我应该对上述 JS 进行哪些更改,以使其仅在第4 个添加/删除feature-block__item-active类 >和第5 位。
我认为,我需要在 Z行, A行和 B行进行更改。
答案 0 :(得分:1)
只需将0更改为3。
document.querySelectorAll('.featured-block .featured-block__item')[3].classList.add('featured-block__item-active'); // Line Z (Adding at 4th element)
const pics = document.querySelectorAll('.featured-block .featured-block__item');
const lastPic = pics.length - 1;
const transitionDuration = 500; // matches CSS
let transitionDelay = 3 * 1000;
const totalDelay = transitionDuration + transitionDelay;
const intervalDelay = (transitionDuration * 2) + transitionDelay;
function toggleClass() {
const activePic = document.querySelector('.featured-block__item.featured-block__item-active');
const activeIndex = Array.prototype.indexOf.call(pics, activePic);
const nextIndex = activeIndex === lastPic ? 3 : activeIndex + 1;
const nextPic = pics[nextIndex];
setTimeout(() => activePic.classList.remove('featured-block__item-active'), transitionDelay);
setTimeout(() => nextPic.classList.add('featured-block__item-active'), totalDelay);
}
setInterval(toggleClass, intervalDelay);
.featured-block__item { border: solid lime 1px;}
.featured-block__item-active{background-color: #DDDDFF;}
<div class="featured-block">
<a href="" class="featured-block__item cf">1 </a>
<a href="" class="featured-block__item cf">2 </a>
<a href="" class="featured-block__item cf">3 </a>
<a href="" class="featured-block__item cf">4 </a>
<a href="" class="featured-block__item cf">5 </a>
</div>