简体   繁体   English

在香草JS中,如何根据滚动条是否位于顶部来从元素中添加或删除类?

[英]In vanilla JS, how can I add or remove a class from an element based on whether the scroll is at the top?

I'm trying to make a sticky nav have a particular class when not scrolled at the top, and not have that class when scrolled at the top. 我试图使粘性导航仪不在顶部滚动时具有特定的类,而在顶部滚动时不具有该类。 Sorry if that's confusing. 抱歉,这令人困惑。

What I'm stuck on right now is the fact that in the bottom piece of code doc.scrollTop == 0 is evaluating to true whenever I scroll the mouse. 我现在停留在的事实是,每当我滚动鼠标时,在底部代码doc.scrollTop == 0中的评估结果为true What am I doing wrong? 我究竟做错了什么?

     HTMLElement.prototype.removeClass = function(remove) {
        var newClassName = "";
        var i;
        var classes = this.className.split(" ");
        for(i = 0; i < classes.length; i++) {
            if(classes[i] !== remove) {
                newClassName += classes[i] + " ";
            }
        }
        this.className = newClassName;
    }  

     window.onscroll = function() {

        var body = document.body; //IE 'quirks'
        var doc = document.documentElement; //IE with doctype
        doc = (doc.clientHeight) ? doc : body;

        if ( doc.scrollTop == 0 ) {
            document.getElementById('top').removeClass('scrolling');
            console.log("doc.scrollTop == 0");//TEST
        } else {
            document.getElementById('top').addClass('scrolling'); // need to make an addClass function ...
            console.log("doc.scrollTop != 0");//TEST
        }
    }; 

Try using this to get the distance from the top: 尝试使用此方法获取与顶部的距离:

var distance = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0);

And in your code: 在您的代码中:

 HTMLElement.prototype.removeClass = function(remove) {
    var newClassName = "";
    var i;
    var classes = this.className.split(" ");
    for(i = 0; i < classes.length; i++) {
        if(classes[i] !== remove) {
            newClassName += classes[i] + " ";
        }
    }
    this.className = newClassName;
}  

 window.onscroll = function() {

    var body = document.body; //IE 'quirks'
    var doc = document.documentElement; //IE with doctype
    doc = (doc.clientHeight) ? doc : body;

    var distance = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0);

    if ( distance === 0 ) {
        document.getElementById('top').removeClass('scrolling');
        console.log("doc.scrollTop == 0");//TEST
    } else {
        document.getElementById('top').addClass('scrolling'); // need to make an addClass function ...
        console.log("doc.scrollTop != 0");//TEST
    }
}; 

Whilst this works, I would strongly suggest looking at improving your JS code to be in line with more modern practices. 尽管这可行,但我强烈建议您考虑改进您的JS代码,使其与更多现代实践保持一致。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM