Javascript滚动事件添加类
大家好,我对滚动事件有问题: 当节在视口中(可见)时,我想向某些链接添加一个类,但问题是如果我的滚动位置在Javascript滚动事件添加类,javascript,scroll,hyperlink,position,viewport,Javascript,Scroll,Hyperlink,Position,Viewport,大家好,我对滚动事件有问题: 当节在视口中(可见)时,我想向某些链接添加一个类,但问题是如果我的滚动位置在选定范围(在if语句)之间,则一切正常类被添加到链接。但是,如果我继续滚动到下一节,类将无限添加。如果语句为真(滚动位置在所选范围之间),如何仅添加它 //元素位置 const attractionSectionPos=数学楼层(ui.attractions\U section.getBoundingClientRect().top); //介绍部分 如果(吸引部分位置=-450){ //如
选定范围
(在if语句
)之间,则一切正常类
被添加到链接
。但是,如果我继续滚动到下一节,类将无限添加。如果语句
为真(滚动位置在所选范围
之间),如何仅添加它
//元素位置
const attractionSectionPos=数学楼层(ui.attractions\U section.getBoundingClientRect().top);
//介绍部分
如果(吸引部分位置=-450){
//如果有多个链接,请删除活动链接
document.querySelectorAll('.active').forEach(link=>link.classList.remove('active'));
//当剖面在视口中时添加类
document.querySelector('[data link=“attractions”]').classList.add('active');
//防止默认值,因此我们只添加一次类
e、 预防默认值();
//如果剖面不在视口中,请删除该类
}else{document.querySelector('[data link=“attractions”]').classList.remove('active')}
如果我添加e.preventDefault()
,它会给我一大堆错误
例如:uncaughttypeerror:E.preventDefault不是一个函数
我在
if语句中添加了以下内容:
!document.querySelector('[data link=“attractions”]').classList.contains('active')
现在,一切都很顺利,当部分位于视口中时,只添加一次类
// Element position
const attractionSectionPos = Math.floor(ui.attractions_section.getBoundingClientRect().top);
// For intro section
if(attractionSectionPos <= 250 && attractionSectionPos >= -450) {
// Remove the active link if we have more than one
document.querySelectorAll('.active').forEach(link => link.classList.remove('active'));
// Add the class when section is in viewport
document.querySelector('[data-link="attractions"]').classList.add('active');
// Prevent default so we only add the class once
e.preventDefault();
// Remove the class if section is not in viewport
} else { document.querySelector('[data-link="attractions"]').classList.remove('active') }