【发布时间】:2014-01-22 02:51:46
【问题描述】:
我的文档中有五个 div,我希望在滚动 div 后,当它们到达特定位置(例如 100 像素)时固定,但某些 div 仅在超出该位置时才会固定。我尝试使用 0px 是相同的东西,但使用 100px 时问题更明显 谁能帮我解决这个问题
css
#f1{
width:600px;
z-index:1;
}
#f2{
width:600px;
z-index:2;
}
#f3{
width:600px;
z-index:3;
}
#f4{
width:600px;
z-index:4;
}
#f5{
width:600px;
z-index:5;
}
.fixed{
position:fixed;
top:100px;
}
js
$( 文档 ).ready(function() { var f1 = $('#f1').offset().top ; var f2 = $('#f2').offset().top ; var f3 = $('#f3').offset().top ; var f4 = $('#f4').offset().top ; var f5 = $('#f5').offset().top ; $(window).scroll(函数(事件){ var y = $(this).scrollTop()+100; 如果 (y >= f1) { $('#f1').addClass('fixed'); } 别的 { $('#f1').removeClass('fixed'); } 如果 (y >= f2) { $('#f2').addClass('fixed'); } 别的 { $('#f2').removeClass('fixed'); } 如果 (y >= f3) { $('#f3').addClass('fixed'); } 别的 { $('#f3').removeClass('fixed'); } 如果 (y >= f4) { $('#f4').addClass('fixed'); } 别的 { $('#f4').removeClass('fixed'); } 如果 (y >= f5) { $('#f5').addClass('fixed'); } 别的 { $('#f5').removeClass('fixed'); } }); });html
<div style="width:600px; margin:0 auto; background:#ccc">
<p>
some long text here
</p>
<div id="f1" style="background:#000; color:#fff">
div 1
</div>
<p>
some long text here
</p>
<div id="f2" style="background:#000; color:#fff">
div 2
</div>
<p>
some long text here
</p>
<div id="f3" style="background:#000; color:#fff">
div 3
</div>
<p>
some long text here
</p>
<div id="f4" style="background:#000; color:#fff">
div 4
</div>
<p>
some long text here
</p>
<div id="f5" style="background:#000; color:#fff">
div 5
</div>
<p>
some long text here
</p>
</div>
你可以在这里看到结果http://jsfiddle.net/hPs6p/
我自己发现了这个问题,谢谢大家
js
$( 文档 ).ready(function() { $(window).scroll(函数(事件){ var y = $(this).scrollTop()+100; var f1 = $('#f1').offset().top ; var f2 = $('#f2').offset().top ; var f3 = $('#f3').offset().top ; var f4 = $('#f4').offset().top ; var f5 = $('#f5').offset().top ; 如果 (y >= f1) { $('#f1').addClass('fixed'); } 别的 { $('#f1').removeClass('fixed'); } 如果 (y >= f2) { $('#f2').addClass('fixed'); } 别的 { $('#f2').removeClass('fixed'); } 如果 (y >= f3) { $('#f3').addClass('fixed'); } 别的 { $('#f3').removeClass('fixed'); } 如果 (y >= f4) { $('#f4').addClass('fixed'); } 别的 { $('#f4').removeClass('fixed'); } 如果 (y >= f5) { $('#f5').addClass('fixed'); } 别的 { $('#f5').removeClass('fixed'); } }); });这个js解决问题
div1、div2、div3、div4 和 div 5 的偏移量是在触发滚动事件之前计算一次的,当 div1 变为固定时,它就没有流量了,其他 div 也是如此 解决方法是在滚动事件中计算div的偏移量,得到一些元素出流后的真实偏移量
【问题讨论】:
标签: jquery html fixed scrolltop exceed