仅当其顶部到达窗口顶部时才修复标题

Header fixed only when its top reached the top of the window

本文关键字:顶部 标题 窗口      更新时间:2023-09-26

我有一个带有类.fullscreen的div,这个类与一个小的JavaScript函数相关联,该函数将使该div显示为全屏。"即div.fullscreen的宽度和高度将是100%"。

//Fullscreen
$(window).on("ready resize", function () {
    if ($(window).width() > 1024) {
        var newHeight = $("html").height() - $("#header").height() + "px";
        $(".fullscreen").css("height", newHeight);
    } else {
        $(".fullscreen").css("height", "auto");
    }
});

因此,高度和宽度不是固定的,而是根据窗口的缩小动态计算的。

在该div 下,还有另一个具有 ID 标头"导航栏",标题最初相对位于div.fullscreen 下方 - 但是,当 #header 顶部到达浏览器窗口顶部时,我试图将其定位为 Fixed。

所以这就是我正在玩的东西,它切换了固定样式,但它没有在正确的位置切换它......

var offset = $('#header').offset();
$(window).scroll(function () {
    $('#header').addClass('fixed-nav');
    if ($(document).scrollTop() < 150) {
        $('#header').removeClass('fixed-nav');
    }
});

所以,我试图整合(var newHeight = $("html").height() + "px";)以下内容,但没有希望:

var newHeight = $("html").height() + "px";
var offset = $('#header').offset();
    $(window).scroll(function () {
        $('#header').addClass('fixed-nav');
        if ($(document).scrollTop() < newHeight) {
            $('#header').removeClass('fixed-nav');
        }
    });

问题的实时示例:http://loai.directory/martin/

您只想在滚动过去.fullscreendiv 时添加fixed-nav类。例如:

$(window).on('scroll', function () {
    if ($(window).scrollTop() >= $(window).height())
        $('.nav').addClass('fixed');
    else
        $('.nav').removeClass('fixed');
});

我在这里使用了$(window).height(),因为我们知道.fullscreen的高度等于窗户的高度,但我们也可以使用 $('.fullscreen').height() .请注意,我们不能使用$('.nav').offset().top因为在 nav 固定后,此偏移量不会提供正确的数字。

请参阅此 JSFiddle。

您还需要添加各种resize侦听器,以便在调整窗口大小时处理更改。