如何在元素到达网页中的某个位置时修复元素的位置?

时间:2012-01-17 01:16:58

标签: javascript html webpage

如果这个问题太愚蠢,请原谅我。我正在制作一个网页,我将有一个由两部分(上部和下部)组成的标题。当我向下滚动页面时,我希望标题的下半部分仍然保留在这里。我该如何实现呢?我打算写一个javascript来处理这个问题 - 一旦下部到达(0,0),它的位置就会从相对位置变为绝对位置。我认为这会奏效,但我只是想知道是否有更好,更简单的方法来做到这一点。 谢谢!

2 个答案:

答案 0 :(得分: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;

}

答案 1 :(得分:0)

结帐jQuery Waypoints。听起来它可能会派上用场。