获取标题的高度,并在滚动到标题之外时显示顶部导航

Get the height of the header and show top navigation when scrolled beyond the header

本文关键字:标题 顶部 导航 显示 滚动 高度 获取      更新时间:2023-09-26

目前,我有这个脚本。700的值放在试错之后。

$(window).scroll(function () {
    if ($(window).scrollTop() > 700) { 
        $('#top_nav').slideDown("slow");
    }
    else{
        $('#top_nav').slideUp("fast");
    }
});

顶部导航栏设置为none

div#top_nav {
    width: 100%;
    z-index: 999;
    opacity: 0.9;
    border-bottom: 1px solid rgb(204, 204, 204);
    box-shadow: 0 0 7px rgb(136, 136, 136);
    position: fixed;
    background-color: rgb(255, 255, 255);
    display: none;
}

我的页眉有以下样式:

#index header {
    background-attachment: fixed;
    background-image: url("../images/bg.jpg");
    background-position: center top;
    background-repeat: no-repeat;
    background-size: cover;
}
我马上就能看出问题所在。我必须手动调整700的值,因为我的标题的高度可能会改变。

我的问题是我如何去改变脚本,使它得到的标题的高度,包括,也许,边距和填充,这样当我滚动,我的顶部导航滑动下来,并显示。

目前工作完美。唯一的问题是700的固定值。必须有一种更可变的方式来做到这一点

尝试与 outerHeight ()

var headerHeight = $('header').outerHeight();
$(window).scroll(function () {
    if ($(window).scrollTop() > headerHeight) { 
        $('#top_nav').slideDown("slow");
    }
    else{
        $('#top_nav').slideUp("fast");
    }
});

编辑:小提琴