”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 如何使用jQuery根据垂直滚动位置添加和删除CSS类?

如何使用jQuery根据垂直滚动位置添加和删除CSS类?

发布于2025-03-23
浏览:745

How Can I Use jQuery to Add and Remove CSS Classes Based on Vertical Scroll Position?

Add/Remove Class with jQuery Based on Vertical Scroll

In this instance, the goal is to remove the class from the "header" element once the user scrolls down a certain distance, and then apply a different class to alter its appearance.但是,提供的代码因某些小错误而无法按预期运行。

有三个主要问题:

比较操作员不正确;应该> =检查滚动位置是否大于或等于500。

删除的类名称被拼写为Clearheader而不是Clearheader。在函数声明的末尾缺少。
$(window).scroll(function() {
    var scroll = $(window).scrollTop();

    // >=, not = 500) {
        // clearHeader, not clearheader - caps H
        $(".clearHeader").addClass("darkHeader");
    }
});
在滚动滚动时重置类,使用第二个条件,如下所示:

通过解决这些问题,您现在可以根据用户的垂直滚动位置有效地从标题中添加和删除类。

最新教程 更多>

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3