2012-07-05 77 views
0

我正在試圖在滾動到某個位置時獲取subnav。但是當它到達那個位置時,它下面的一切都會上移。不能弄清楚它是什麼。可能非常簡單,我只是沒有看到它。感謝您的幫助滾動時固定的元素

CSS

#subnav ul{ 
list-style: none; 
} 
#subnav a:visited{ 
color: #000; 
text-decoration: none; 
} 
#subnav a{ 
color: #000; 
text-decoration: none; 
} 
#subnav.fixed{ 
position:fixed; 
top:0; 
} 
.main { 
-webkit-border-top-right-radius:10px; 
-webkit-border-top-left-radius:10px; 
-moz-border-radius-topleft:10px; 
-moz-border-radius-topright:10px; 
border-top-left-radius:10px; 
border-top-right-radius:10px; 
min-height: 500px; 
height: auto; 
width: 700px; 
-moz-box-shadow: -1px 1px 1px 1px #ccc; 
-webkit-box-shadow: -1px 1px 1px 1px #ccc; 
box-shadow:   -1px 1px 1px 1px #ccc; 
float: none; 
font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif; 
z-index:1000; 
    position: relative; 
font-size: 12px; 
background-color: #FFF; 
background-position: left top; 
padding-top: 15px; 
padding-right: 15px; 
padding-bottom: 15px; 
padding-left: 15px; 
margin-bottom: -200px; 
} 

HTML

<div id="subnav"> 
     <ul> 
      content 
     </ul> 
    </div> 

    <div class="main"> 
     <div class="imageholder"> 
      content 
     </div> 

     <div class="text"> 
      content 
     </div> 
    </div> 

$(document).ready(function() { 
var top = $('#subnav').offset().top - parseFloat($('#subnav').css('marginTop').replace(/auto/, 0)); 
$(window).scroll(function (event) { 
// what the y position of the scroll is 
var y = $(this).scrollTop(); 

// whether that's below the form 
if (y >= top) { 
    // if so, ad the fixed class 
    $('#subnav').addClass('fixed'); 
} else { 
    // otherwise remove it 
    $('#subnav').removeClass('fixed'); 
} 
}); 
}); 
+0

你是說當滾動條從「靜態」定位到「固定」定位時,內容似乎'跳躍'了嗎? – jackwanders 2012-07-05 13:35:10

+0

您需要爲底部的對接設置一個自定義類,至少這就是我正在使用的類,如果它不在頂部並且不固定,請添加此邊距並使其停靠頁腳。 – Alexandre 2012-07-05 13:51:38

回答

1

我知道這個問題一年半前被問過,但我的情況下,回答反正它可以幫助別人的未來...

我最近遇到了同樣的問題在現場工作時。就像丹尼爾說的那樣,它會跳躍起來,因爲你正在從流程中刪除#subnav,這就是設置「固定」位置的原因。它本質上是做同樣的事情,就好像你要完全刪除你的#subnav元素:跳起來填補空白。

爲了解決這個問題,當滾動到固定點時,我創建了一個具有所有相同尺寸,填充,邊距等的新div,以便在修復#subnav時實質上「填充」。您可以通過以下幾種方式來完成這項工作:使用添加/刪除「固定」類時顯示/隱藏的不同ID創建重複的隱藏div,或者使用JS動態創建一個。無論您在此選擇何種解決方案,都可以避免跳躍問題。

例子:

$(window).scroll(function (event) { 
    var y = $(this).scrollTop(); 

    if (y >= top) { 
     $('#subnav').addClass('fixed') 
     .after("<div id='filler'></div>"); // Add the new "filler" div 

     // Make the height, width, padding-top, padding-bottom, margin-top, and 
     // margin-bottom the same as the #subnav 
     $('#filler') 
      .css("height", $('#subnav').css("height")) 
      .css("width", $('#subnav').css("width")); // etc 

    } else { 
     $('#subnav').removeClass('fixed'); 

     // Remove the filler 
     $('#filler').remove(); // Or you can hide and show it again as needed 
    } 
}); 

希望這有助於。乾杯!

2

休息,因爲你正在服用的#subnav了直列流的上升。