If语句- If主体有一个类remove在滚动原生javascript

if statement - if body has a class remove on scroll native javascript

本文关键字:If 滚动 原生 javascript remove 语句 主体 有一个      更新时间:2023-09-26

我试图使用原生javascript,所以没有jquery加载。我想使一个if语句删除类在元素只有当它有一个类。这样我就可以避免每次出现卷轴时触发它。我基本上想让它删除类只有当窗口滚动和主体有这个类应用到它,否则它不应该触发。

我尝试了这段代码,它确实删除了类,但它总是触发滚动,无论身体是否有一个类或不应用于它。在这种情况下……我看到控制台上的scrollEvent打印了我在页面上做的每一个滚动。你是怎么做这项工作的?

if(document.body.classList){
    window.addEventListener('scroll', function(){
        console.log('scrollEvent');
        document.body.classList.remove('mobile-menu-open');
    });
}

你的if需要检查这个类

window.addEventListener('scroll', function(){
    console.log('scrollEvent');
    // do the following only if it has the class
    if( document.body.classList.contains('mobile-menu-open') ) {
       document.body.classList.remove('mobile-menu-open');
    }
});

你可以删除侦听器,一旦你的类从body中删除,这样当你滚动时它就不会再触发了。

代码如下:

var removeMenuClass = function() {
    document.body.classList.remove('mobile-menu-open');
    // remove the scroll listener
    window.removeEventListener('scroll', removeMenuClass, false);
}
// add the scroll listener
window.addEventListener('scroll', removeMenuClass, false);

如果需要(比如当你的"mobile-menu"重新打开时),你可以用同样的方式重新附加eventListener