簡體   English   中英

滾動時嘗試使導航菜單停留在屏幕頂部

[英]Trying to make nav menu stick at top of screen when scrolling

滾動時,我正在使菜單停留在頂部。 我在這里跟隨一個例子: 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' });
    }
});

您需要像這樣將左: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/

問題是,當您添加position: fixed到元素時,它將使元素脫離文檔流。 它位於使它們保持浮動的所有其他元素之上。

您有right: 0 nav樣式為right: 0 只要絕對定位,它就會粘在其父對象的右側。

當您將其更改為固定位置時,它也將粘貼在其父對象的右側,在這種情況下就是視口。

您可以通過在固定狀態下更改位置來修復它:

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

還要檢查此更新的Fiddle

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM