2012-01-17 68 views
1

如果這個問題太愚蠢,請原諒我。我正在製作一個網頁,其中包含兩部分(上部和下部)。當我向下滾動頁面時,我希望標題的下部仍然留在此處。我怎樣才能實現這個?我打算編寫一個JavaScript來處理這個問題 - 一旦下半部分達到(0,0),它的位置將從相對變爲絕對。我認爲這是可行的,但我只是想知道是否存在一個更好,更簡單的方法來做到這一點。 謝謝!如何在元素到達網頁中的某個位置時修復元素的位置?

+0

根據所要支持的瀏覽器/版本,['位置:fixed'(http://davidwalsh.name/css-fixed-position)可能會爲你工作。 – 2012-01-17 01:20:21

+0

@JaredFarrish - 固定位置是他需要的,不要忘記它仍然需要JavaScript。他不希望標題的下半部分停留在屏幕中間。 – 2012-01-17 01:22:59

+0

@JosephSilber - 請記住,如果這是一個完整的答案,它不會是一個評論。 ')' – 2012-01-17 01:25:38

回答

2

檢查這個動作:http://jsfiddle.net/JLETx/4/

更新:固定的 「跳樓內容」

HTML

<div id="topHeader">top header</div> 
<div id="bottomHeader">bottome header</div> 
<div id="extremelyLongContent"> long content here </div> 

JS

var initial = $('#bottomHeader').offset(); 

$(document).scroll(function() { 
if ($(this).scrollTop() > initial.top) { 
    $('#bottomHeader').css('position', 'fixed'); 
    $('#topHeader').css('margin-bottom', initial.top+'px'); 
    $('#bottomHeader').css('top','0'); 
} 
else { 
    $('#bottomHeader').css('position', 'static'); 
    $('#topHeader').css('margin-bottom', 0); 
} 

}); 

CSS

body{ 
position:relative; 
} 

#topHeader{ 
background:red; 
height:100px; 
} 
#bottomHeader{ 
background:blue; 
height:100px; 
width:100%; 
} 

#extremelyLongContent{ 
background:green; 
height:1000px; 

}