简体   繁体   English

滚动后固定导航栏?

[英]Navigation bar fixed after scroll?

I have a navigation bar after header and i want that to be stuck at top of the page while scrolling down.我在 header 之后有一个导航栏,我希望它在向下滚动时停留在页面顶部。

can i do with position:relative ??我可以使用position:relative吗?? Unlike position:fixed with the help of the following script or any other better way?与 position 不同:借助以下脚本或任何其他更好的方法修复?

$(window).scroll(function () {
if ($(window).scrollTop() > 100) {
    $('#header').css('top', $(window).scrollTop());
}});

here is my fiddle !这是我的小提琴

black color background bar to be stuck at the top of the page黑色背景条卡在页面顶部

please help me out to fix that, thank you in advance.请帮我解决这个问题,在此先感谢您。

Is this what you're trying to get? 是您想要得到的吗?

window.onscroll = changePos;

function changePos() {
    var header = document.getElementById("header");
    if (window.pageYOffset > 70) {
        header.style.position = "fixed";
        header.style.top = "0";
    } else {
        header.style.position = "";
        header.style.top = "";
    }
}

Update: (I think, not sure) you can't scroll a fixed element, but you can an absolute one. 更新:(我认为,不确定)您不能滚动固定元素,但可以滚动绝对元素。 So in the code below we're using position: absolute but making it behave like it's fixed . 因此,在下面的代码中,我们使用position: absolute但使其行为像fixed Now you can see the #header when you zoom in and scroll down. 现在,您可以在放大和向下滚动时看到#header

window.onscroll = changePos;

function changePos() {
    var header = document.getElementById("header");
    if (window.pageYOffset > 70) {
        header.style.position = "absolute";
        header.style.top = pageYOffset + "px";
    } else {
        header.style.position = "";
        header.style.top = "";
    }
}

FIDDLE 小提琴

you can solve it with css:你可以用css解决它:

html: html:

    <nav id= "header">
      <ul>
        <li><a href="#"> Link 1 </a></li>
        <li><a href="#"> Link 2 </a></li>
        <li><a href="#"> Link 3 </a></li>
      </lu>
    </nav>

css: css:

    #header{
    position: sticky;
    top: 0; /* Position where u want it to stick, can be a
               percentage, px, vh or any position unit */
    z-index:150; /* to keep it on top layer in order not to be 
                    masked by another element*/
    }

check this link: https://elextutorial.com/learn-css/css-position-fixed-scroll-sticky/检查此链接: https://elextutorial.com/learn-css/css-position-fixed-scroll-sticky/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM