[英]add class to element in viewport
我的页面上有五个部分,我正在尝试将类“活动”添加到视口中的部分。 我试过这段代码,但它不能正常工作。 代码将所有带有标签名称“section”的元素保存在一个节点列表中,然后创建了这个列表的数组,我遍历了数组并为每个元素添加了一个事件侦听器,然后我测试了该元素是否在视口中,所以我添加类,否则我删除类。 问题是一旦页面滚动,所有五个部分都将具有“活动”类,这意味着多个元素同时具有“活动”类,即使在端口中仅查看一个部分并且当我继续滚动时向下移出视口的部分已删除其“活动”类。 我怎样才能一次拥有一个带有“活动”类代码图像的元素?
//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 > window.innerHeight || bottom+height < window.innerHeight ) { 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.