纯js在滚动x数量后添加和删除(切换)类?

Joh*_*911 4 javascript

我不想为此使用 jQuery。

这真的很简单,我只想在滚动经过一定数量的像素(比如 10 像素)后添加一个类,如果我们回到前 10 个像素,就将其删除。

我最好的尝试是:

var scrollpos = window.pageYOffset;
var header = document.getElementById("header");

function add_class_on_scroll() {
    header.classList.add("fade-in");
}

function remove_class_on_scroll() {
    header.classList.remove("fade-in");
}

window.addEventListener('scroll', function(){
    if(scrollpos > 10){
        add_class_on_scroll();
    }
    else {
        remove_class_on_scroll();
    }
    console.log(scrollpos);
});
Run Code Online (Sandbox Code Playgroud)

但是控制台显示的数字无论向上或向下滚动都会继续增长。fade-in尽管控制台显示我们已经超过 10级,但该类从未被添加。

Fil*_*ker 10

您忘记更改滚动处理程序中的偏移值。

//use window.scrollY
var scrollpos = window.scrollY;
var header = document.getElementById("header");

function add_class_on_scroll() {
    header.classList.add("fade-in");
}

function remove_class_on_scroll() {
    header.classList.remove("fade-in");
}

window.addEventListener('scroll', function(){ 
    //Here you forgot to update the value
    scrollpos = window.scrollY;

    if(scrollpos > 10){
        add_class_on_scroll();
    }
    else {
        remove_class_on_scroll();
    }
    console.log(scrollpos);
});
Run Code Online (Sandbox Code Playgroud)

现在你的代码工作正常

解释

没有像您要求的那样的文档。这只是逻辑工作流中的一个问题。

当您说scrollpos = window.scrollY您的页面顶部偏移量为 0 时,您的变量将存储该值。当页面滚动时,您的scroll侦听器将被触发。当然,当您侦听器检查该scrollpos值时,该值仍然0是 。但是,如果在每个滚动处理程序中更新该scrollpos值,现在您就可以拥有一个动态值。

另一种选择是您创建一个吸气剂,例如

var scrollpos = function(){return window.scrollY};
Run Code Online (Sandbox Code Playgroud)

通过这种方式,您可以动态检查该方法将在每个偏移处为您返回的内容。

if(scrollpos() > 10)
Run Code Online (Sandbox Code Playgroud)

看?希望有所帮助。(: