javascript 滚动后导航栏固定吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20594452/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 18:50:33  来源:igfitidea点击:

Navigation bar fixed after scroll?

javascriptjqueryhtmlcss

提问by stacky

I have a navigation bar after header and i want that to be stuck at top of the page while scrolling down.

我在标题后有一个导航栏,我希望在向下滚动时将其卡在页面顶部。

can i do with position:relative?? Unlike position:fixed with the help of the following script or any other better way?

我可以用position:relative做吗??与位置不同:借助以下脚本或任何其他更好的方式修复?

$(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.

请帮我解决这个问题,提前谢谢你。

回答by akinuri

Is thiswhat 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: absolutebut making it behave like it's fixed. Now you can see the #headerwhen you zoom in and scroll down.

更新:(我认为,不确定)您不能滚动固定元素,但可以绝对滚动。因此,在下面的代码中,我们正在使用,position: absolute但使其表现得像fixed. 现在您可以#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

小提琴