如何用JS querySelector选择div下除末尾子元素外的元素并修复滚动异常
修复客户评价横向滚动按钮的异常问题
当前点击滚动按钮时会出现无评价内容的空白情况,原因是JS代码选中了.SecondDiv_tablet下的所有子元素,其中包含导航按钮(.navigation-buttons)和分页(.swiper-pagination)这些非评价元素,导致切换索引时会定位到这些无关元素上。
修复方案
只精准选中所有带有.testimonials类的评价容器,而非父元素下的全部子元素。
修改后的JavaScript代码
const previous = document.querySelector('.previous'); const next = document.querySelector('.next'); // 仅选中.SecondDiv_tablet下所有带testimonials类的元素 const images = document.querySelectorAll('.SecondDiv_tablet .testimonials'); const totalImages = images.length; let currentIndex = 0; // 按钮点击事件监听 previous.addEventListener('click', previousImage) next.addEventListener('click', nextImage) // 切换到下一条评价 function nextImage(){ images[currentIndex].classList.remove('main'); currentIndex = currentIndex === totalImages - 1 ? 0 : currentIndex + 1; images[currentIndex].classList.add('main'); } // 切换到上一条评价 function previousImage(){ images[currentIndex].classList.remove('main'); currentIndex = currentIndex === 0 ? totalImages - 1 : currentIndex - 1; images[currentIndex].classList.add('main'); }
关键修改点说明
- 替换元素选择逻辑:将
document.querySelector('.SecondDiv_tablet').children改为document.querySelectorAll('.SecondDiv_tablet .testimonials'),精准筛选所有评价容器,排除导航按钮、分页等无关元素。 - 索引循环逻辑适配:
totalImages现在对应有效评价项的数量,切换时只会在评价内容间循环,不会定位到空白元素。
内容的提问来源于stack exchange,提问作者lLizzy
相关产品推荐
相关产品推荐

