【问题标题】:In vanilla JS, how can I add or remove a class from an element based on whether the scroll is at the top?在 vanilla JS 中,如何根据滚动是否在顶部从元素中添加或删除类?
【发布时间】:2016-02-03 09:32:07
【问题描述】:

我试图让粘性导航在顶部不滚动时具有特定的类,而在顶部滚动时不具有该类。对不起,如果这令人困惑。

我现在坚持的事实是,每当我滚动鼠标时,底部代码 doc.scrollTop == 0 的计算结果为 true。我做错了什么?

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

【问题讨论】:

  • protip:你所谓的removeClassalready exists in vanilla JS,就是element.classList.remove(...)函数。同样,addtoggle 已经存在(阅读现代 HTML 可能是个好主意)。另外,不要使用 15 岁以上的 window.onscroll,使用适当的现代 window.addEventListener("scroll", function(evt) {...}); 事件处理。最后,看看getBoundingClientRect

标签: javascript


【解决方案1】:

尝试使用它来获取与顶部的距离:

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 代码以符合更现代的做法。

【讨论】:

    猜你喜欢
    • 2021-10-28
    • 1970-01-01
    • 1970-01-01
    • 2017-10-27
    • 1970-01-01
    • 2016-03-16
    • 2018-04-10
    • 1970-01-01
    • 2021-06-18
    相关资源
    最近更新 更多