JQUERY:为什么不;向下滚动时,我的导航固定在顶部

JQUERY: why isn't my nav fixed to the top when scrolling down?

本文关键字:导航 我的 顶部 为什么不 滚动 JQUERY      更新时间:2023-09-26

当你在页面上向下滚动100px时,我的导航栏会固定在顶部。然后当向上滚动时,它返回到其正常状态。

我已经设法使导航栏在滚动时变得固定和不固定,但它不在正确的位置。它将页面向下固定到左侧,而不是顶部并向右浮动。

这是我在jsfiddle上做的例子,供你看看。

http://jsfiddle.net/edL5F/20/

       <div id="wrapper">
            <div id="codeback">
            </div>
            <div id="container">
                 <div class="nav">
                 </div>
                 <div id="wrap">
                 </div>
            </div><!-- END OF CONTAINER -->
       </div>

 body{
    background-color:black;
}
    #wrapper{
        width:100%; 
        height:inherit;
    }
    #codeback{
        width:100%;
        height:100%;
        background-image:url('capture.jpg');
          background-repeat: no-repeat;
        position:fixed;
        left:0px;
        top:0px;
        z-index:-1;
    }
    #container{
        width:100%;
        float:right;
    }
    .nav{
        margin-top:100px;
        width:80%;
        height:50px;
        float:right;
        background-color:blue;
        position:relative;
    }

    #wrap{
        float:right;
        width:80%;
        height:1500px;
        background-color:white;
    }


 $(window).scroll(function (e) {
    $el = $('.nav');
    if ($(this).scrollTop() > 100 && $el.css('position') != 'fixed') {
        $('.nav').css({ 'position': 'fixed', 'top': '0'});
    }
    if ($(this).scrollTop() < 100 && $el.css('position') == 'fixed') {
        $('.nav').css({ 'position': 'relative'});
    }
});

你可以用class。。。

$(window).scroll(function (e) {
    $el = $('.nav');
    if ($(this).scrollTop() > 100) {
        $('.nav').addClass("fixedNav");
    }else {
        $('.nav').removeClass("fixedNav");
    }
});
.fixedNav {
    position:fixed;
    margin:0;
    width:100%;
}

小提琴在这里:http://jsfiddle.net/yss9hz0v/

float:right在位置为fixed时没有任何影响。因此,当您将元素设置为位置fixed时,必须设置right:0px

最后,每次将元素位置从fixed更改为relative,再更改为0px100px时,都必须更改margin-top分别

尝试:

$(window).scroll(function (e) {
    $el = $('.nav');
    if ($(this).scrollTop() > 100 && $el.css('position') != 'fixed') {
        $('.nav').css({ 'position': 'fixed', 'top': '0','right':'0','margin-top':'0px'});
    }
    if ($(this).scrollTop() < 100 && $el.css('position') == 'fixed') {
        $('.nav').css({ 'position': 'relative','margin-top':'100px'});
    }
});

演示

这是我的解决方案:

  1. .nav中删除margin-top
  2. padding-top:100px添加到#container
  3. 编辑jquery

Jquery:

$(window).scroll(function (e) {
    $el = $('.nav');
    if ($(this).scrollTop() > 100 && $el.css('position') != 'fixed') {
        $('.nav').css({ 'position': 'fixed', 'top': '0','right':'0'});
    }
    if ($(this).scrollTop() < 100 && $el.css('position') == 'fixed') {
        $('.nav').css({ 'position': 'relative','margin-top':'100px'});
    }
});

这是一把小提琴。

说明:CCD_ 14是在CCD_。

边距到填充的变化是在不编辑任何css的情况下,当你向上滚动时,迫使条回到原来的位置。

因为.nav元素的css属性中有一个margin-top: 100px;。。。

Fiddle:http://jsfiddle.net/edL5F/24/