我的页面上有五个部分,我正试图添加类"活动";到视图端口中的部分。我试过这个代码,但它不能正常工作。代码保存所有标签名为"section"的元素。在节点列表中,然后创建了这个列表的数组,我循环数组并为每个元素添加了一个事件侦听器,然后我测试了元素是否在视口中,所以我添加了类,否则我删除了类。问题是,一旦页面滚动,所有的五个部分都会有"活动"类。这意味着多个元素都有"active"这个类。同时,即使只有一个部分在端口中被查看,当我继续向下滚动时,向上移动的部分有他们的类&活动"移除。我怎么能有一个元素与类"活动"图像的代码?
//values of viewport
const viewWidth = document.documentElement.clientWidth;
const viewHeight = document.documentElement.clientHeight;
//set class active to section in viewport
function sectionInView(x) {
for (let i = 0; i in x; i++) {
document.addEventListener("scroll", function () {
let el = x[i].getBoundingClientRect();
if (el.top >= 0 && el.left >= 0 && el.bottom <= viewHeight && el.right <= viewWidth) {
x[i].setAttribute("class", "active your-active-class");
}
else {
x[i].removeAttribute("class", "active your-active-class");
}
});
}
}
sectionInView(sectionListArray);
let sectionListArray = document.querySelectorAll('section')
const viewHeight = document.documentElement.clientHeight
window.onscroll = (() => {
sectionListArray.forEach(function(v) {
let rect = v.getBoundingClientRect();
let y = rect.y;
let bottom = rect.bottom;
let height = rect.height;
if (y > viewHeight|| bottom+height < viewHeight ) {
v.classList.add('active')
} else {
v.classList.remove('active')
}
})
})
section {
height: 300px;
background: red;
margin-bottom: 10px;
transition: 1s;
opacity:1
}
.active{
opacity:0
}
<section></section>
<section></section>
<section></section>
<section></section>
<section></section>
<section></section>
<section></section>
<section></section>
<section></section>