在vanilla JS中,如何根据滚动是否位于顶部来添加或删除元素中的类? [英] In vanilla JS, how can I add or remove a class from an element based on whether the scroll is at the top?

查看:62
本文介绍了在vanilla JS中,如何根据滚动是否位于顶部来添加或删除元素中的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使粘性导航在顶部不滚动时具有特定类,并且在顶部滚动时不具有该类。对不起,如果那令人困惑。

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.

我现在坚持的是在底部的代码中 doc.scrollTop == 0 正在评估 true 。我做错了什么?

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. 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);

在您的代码中:

 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
    }
}; 

虽然这有效,但我强烈建议改善你的JS代码,使其更符合现代做法。

Whilst this works, I would strongly suggest looking at improving your JS code to be in line with more modern practices.

这篇关于在vanilla JS中,如何根据滚动是否位于顶部来添加或删除元素中的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆