根据滚动位置更改 CSS 类

change css class based on scroll position

本文关键字:CSS 位置 滚动      更新时间:2023-09-26

我有以下HTML

<header class="fixed">...</header>
<div id="content">
    <div id="sidemenu" class="fixed">...</div>
    <div id="scroll">...</div>
</div>
<footer class="fixed">...</footer>

在CSS和规则中使用各种定位规则

.fixed {
    position: fixed;
}

这实现了仅具有 id 的div 滚动移动的预期效果。但是,这可能会使页脚不在视线之外。

我想做的是,一旦滚动div的底部到达页脚的底部,position: fixed更改为position: absolute,然后所有内容将一起向上滚动,显示页脚。

但我不知道该怎么做。我正在看航点,但我有点头疼。

这样的事情应该可以解决你的问题。 试试这个:

$(window).scroll(function () {
    var scrollBottom = $(document).height() - $(window).height() - $(window).scrollTop();
    if (scrollBottom <= $("footer").height()) {
        $("footer").css("position", "absolute");
        } 
        else {
            $("footer").css("position", "fixed");
        }
});

为此,您将有"onScroll"事件。并检查滚动div 的坐标何时与页脚的坐标匹配。一旦它们匹配,在处理程序的实现中将位置更改为"绝对"。