从滚动上的任意位置创建固定位置元素
Creating a fixed position element from arbitrary position on scroll
我有一个固定的 header,当有人向下滚动到该元素时,我想在 header 下面添加一个额外的固定元素。我已经非常接近它了,除了当我滚动时新的固定元素会跳来跳去,我不知道为什么。
$(window).scroll(function() {
height2 = $('#product_nav_cont').offset().top;
scroll2 = $(this).scrollTop();
header2 = $('#scroll_header_cont').outerHeight();
pos2 = height2-header2
if(scroll2 > pos2) {
$('#product_nav_cont').css({'position':'fixed','top':header2,'width':'100%'});
} else {
$('#product_nav_cont').css({'position':'static','top':'0'});
}
});
我认为这可能与变量 "height2" 有关甚至是问题。非常感谢任何想法。
查看问题
您应该将变量 header2 和 height2 放在滚动函数之外。这是您的 updated fiddle 和新代码:
header2 = $('#scroll_header_cont').outerHeight();
height2 = $('#product_nav_cont').offset().top;
$(window).scroll(function() {
scroll2 = $(this).scrollTop();
pos2 = height2-header2
if(scroll2 > pos2) {
$('#product_nav_cont').css({'position':'fixed','top':header2,'width':'100%'});
} else {
$('#product_nav_cont').css({'position':'static','top':'0'});
}
});
我有一个固定的 header,当有人向下滚动到该元素时,我想在 header 下面添加一个额外的固定元素。我已经非常接近它了,除了当我滚动时新的固定元素会跳来跳去,我不知道为什么。
$(window).scroll(function() {
height2 = $('#product_nav_cont').offset().top;
scroll2 = $(this).scrollTop();
header2 = $('#scroll_header_cont').outerHeight();
pos2 = height2-header2
if(scroll2 > pos2) {
$('#product_nav_cont').css({'position':'fixed','top':header2,'width':'100%'});
} else {
$('#product_nav_cont').css({'position':'static','top':'0'});
}
});
我认为这可能与变量 "height2" 有关甚至是问题。非常感谢任何想法。
查看问题您应该将变量 header2 和 height2 放在滚动函数之外。这是您的 updated fiddle 和新代码:
header2 = $('#scroll_header_cont').outerHeight();
height2 = $('#product_nav_cont').offset().top;
$(window).scroll(function() {
scroll2 = $(this).scrollTop();
pos2 = height2-header2
if(scroll2 > pos2) {
$('#product_nav_cont').css({'position':'fixed','top':header2,'width':'100%'});
} else {
$('#product_nav_cont').css({'position':'static','top':'0'});
}
});