简体   繁体   English

用JavaScript定位元素时遇到问题

[英]Trouble with positioning of element with javascript

I'm trying to achieve a navigation bar which is "catched" as the user scrolls to it. 我正在尝试实现一个导航栏,该导航栏在用户滚动到它时被“捕获”。 I am semi achieving my goal but with my current attempt this is also moving my main content as I scroll which is not what I want to achieve. 我正在实现目标,但通过当前的尝试,这也在移动我滚动的主要内容,而这并不是我想要实现的。 Here's what I have https://jsfiddle.net/abp1rwhp/ 这是我的https://jsfiddle.net/abp1rwhp/

$(function(){
var navHeight = $('#nav-bar').offset().top;
console.log(navHeight)
$(window).on('scroll', function() {
    if(screen.width < 980) {
    }
    if($(window).scrollTop() > navHeight){
        $('#nav-bar').css({
            'top': $(window).scrollTop() > 0 ? '0px' : '0px',
            'position': 'fixed'
        })
    }
    if($(window).scrollTop() < navHeight){
        $('#nav-bar').css({
            'top': '',
            'position': 'relative'
        })
    }
});
})

As you can see the content section moves down (I think 40px) when you scroll, how would I go about fixing this issue? 如您所见,滚动时内容部分向下移动(我认为40px),我该如何解决该问题?

Because the Nav-bar is originally relative, it pushes down the contents section. 由于导航栏最初是相对的,因此它会向下推动内容部分。 When you give it position fixed, the section goes up, because the Nav-bar no longer uses that space in the page. 当您将其位置固定时,该部分会上升,因为导航栏不再使用页面中的该空间。

To combat this, you could give the section a margin-top of 40px, when you give the nav-bar position relative, so that that 40px space is kept. 为了解决这个问题,当您将导航栏的位置设为相对位置时,可以为该部分的上边距设置为40px,以便保留40px的空间。

I was able to solve your problem by rewriting the CSS in your two if statements like this: 我可以通过在两个if语句中重写CSS来解决您的问题,如下所示:

    if ($(window).scrollTop() > navHeight) {
        $('#nav-bar').css({
            'top': '0px',
            'position': 'fixed'
        });
    }

    if ($(window).scrollTop() < navHeight) {
        $('#nav-bar').css({
            'top': '80px',
            'position': 'absolute'
        });
    }

You don't want your #nav-bar to be relative because that re-inserts it into the flow of the document, pushing the contents down. 您不希望#nav-bar是相对的,因为那样会将其重新插入到文档流中,从而将内容压低。 In other words, it is laid out the way it would normally be and then applies any positioning from top, left, etc. after that. 换句话说,它按照通常的方式进行布局,然后在此之后从顶部,左侧等位置应用任何定位。

Instead, I made it absolute with the position from the top (80px) it has initially when the document loads. 取而代之的是,我将文档加载时的顶部位置(80像素)设为绝对位置。

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

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