2014-02-21 99 views
1

我正在滚动时使我的菜单棒顶部。我在这里举一个例子: https://stackoverflow.com/a/1216130/571723试图使滚动菜单棒滚动时在屏幕顶部

但是我的菜单是在一个较小的居中div。当菜单位于顶部的“粘贴”位置时,菜单会被移到页面的右侧。这里是我的小提琴:http://jsfiddle.net/edL5F/1/

如何让菜单留在容器内,而将其设置为固定?

CSS:

.content-wrapper { 
    margin: 0 auto; 
    max-width: 800px; 
    position: relative; 
    background-color: #cccccc; 
} 

nav { 
    position: absolute; 
    right: 0; 
    top: 63px; 
    margin-top: 5px; 
    font-size: 1.3em; 
    font-weight: 600; 
    list-style:none; 
    width:628px; 
    margin:5px auto; 
    height:43px; 
    padding:0px 10px 0px 10px; 
    z-index: 10; 

    /* Rounded Corners */ 
    /*border-radius: 10px; */ 

    /* Background color and gradients */ 
    background: #014464; 
    background: -moz-linear-gradient(top, #0272a7, #013953); 
    background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#0272a7), to(#013953)); 

    /* Borders */ 
    border: 1px solid #002232; 

    box-shadow: inset 0px 0px 1px #edf9ff; 
} 

div.divBlock { 
    margin: 20px 0; 
} 

JS:

$(window).scroll(function (e) { 
    $el = $('nav'); 
    if ($(this).scrollTop() > 80 && $el.css('position') != 'fixed') { 
     $('nav').css({ 'position': 'fixed', 'top': '-10px'}); 
    } 
    if ($(this).scrollTop() < 80 && $el.css('position') == 'fixed') { 
     $('nav').css({ 'position': 'absolute', 'top': '63px' }); 
    } 
}); 

回答

2

你需要把左:150,右:0给你的函数是这样的:

$(window).scroll(function (e) { 
     $el = $('nav'); 
     if ($(this).scrollTop() > 80 && $el.css('position') != 'fixed') { 
      $('nav').css({ 'position': 'fixed', 'top': '-10px', 'left':'150px', 'right':'0'}); 
     } 
     if ($(this).scrollTop() < 80 && $el.css('position') == 'fixed') { 
      $('nav').css({ 'position': 'absolute', 'top': '63px', 'left':'', 'right':'' }); 
     } 
    }); 

这里是工作的jsfiddle :http://jsfiddle.net/k49n4/

+0

对不起,我更新了工作示例的代码.. –

+0

关闭。切换到固定状态时,导航栏仍会覆盖图片的一部分。 – dmikester1

+0

只要把'左':'150px'而不是'左':'0',它应该这样做.. –

0

问题是,当您将position: fixed添加到元素时,它会将该元素从文档流中取出。它坚持在所有其他保持浮动的元素之上。

您的nav风格中有right: 0。只要它是绝对定位的,它就会坚持到其父母的右侧。

当您将其更改为固定位置时,它也会固定在它的父级右侧,在这种情况下是视口。

你可以通过改变在固定状态下的位置修正:

$('nav').css({ 
    'position': 'fixed', 
    'top': '-10px', 
    'left': '50%', 
    'margin-left': '-250px' /* container width - image width */ 
}); 

还要检查这个updated Fiddle