[英]Div positioning fixed at margin-top:20px when scrolling up
I have a div which I want to become fixed at 20px from the top of the window when you scroll up and 40px from the footer when you get the bottom. 我有一个div,当您向上滚动时,我希望将其固定在离窗口顶部20px处;当到达底部时,我要将其固定于页脚40px。 My code seems inconstant, there must be a better way?
我的代码似乎不固定,必须有更好的方法吗? Page Link
页面链接
$(document).scroll(function () {
if($(window).scrollTop() >= 345){
$('#rightShipping').css({'position' : 'fixed', 'top' : '0px'});
}
if($(window).scrollTop() <= 346){
$('#rightShipping').css({'position' : '', 'top' : ''});
}
console.log($(window).scrollTop());
});
One quick idea - I would remove the .rightCol
block, leaving only the #rightShipping
one with top: 20px
and it parent with position: relative
. 一个简单的主意-我将删除
.rightCol
块,只保留#rightShipping
一个, top: 20px
,其父级为position: relative
。 And then use this code: 然后使用以下代码:
$(document).scroll(function () {
var scrollTop = $(window).scrollTop();
var offsetTop = $('#rightShipping').offset().top;
var positionTop = $('#rightShipping').position().top;
if (scrollTop >= offsetTop - positionTop) {
$('#rightShipping').css('position', 'fixed');
} else {
$('#rightShipping').css('position' : 'relative');
}
});
I really don't know if this will work, as I haven't tested it and I need to get some sleep, but I hope it helps. 我真的不知道这是否行得通,因为我还没有测试过,所以我需要睡觉,但是我希望它能有所帮助。
Good luck! 祝好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.