2012-01-17 65 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; 

}