我在向产品页面添加滚动条“添加到购物车”区域时遇到一些问题。
到目前为止,我能够使所选元素在滚动时从某个点变为 position:fixed
,直到它到达“截止点”,可以这么说,在那里它变为 position :绝对
。
我还编写了一条规则,用于在滚动到position:fixed
的“起点”上方时删除位置样式。所有这些都写在一个函数内,该函数在 $(document).scroll()
上触发。我将在下面发布我的代码。
除了一件特定的事情之外,我编写的规则似乎运行良好。当我向下滚动时,该元素变得固定。当固定元素到达“截止点”时,它会切换到 position:absolute
并在我继续滚动时保持在那里。这就是我想要的。
问题是当我开始向后滚动超过“截止点”时,元素的位置不会切换回 位置:固定
。 它保持 position:absolute
直到我到达删除样式的页面顶部。然后我可以再次向下滚动,它就会开始再次,固定 > 绝对 > 向上滚动时不会恢复到固定状态。
function checkOffset() {
var div1 = $(".ProductMain");
var div2 = $(".SideRelatedProducts");
var div3 = $("#cssmenu");
var div1_top = div1.offset().top;
var div2_top = div2.offset().top;
var div3_top = div3.offset().top;
var div1_bottom = div1_top + div1.height();
var div2_bottom = div2_top + div2.height();
var div3_bottom = div3_top + div3.height();
// This is what removes styling assigned from scrolling, when element gets back to top of page
if (div1_bottom >= div3_bottom && $(window).width() > 900) {
$('.ProductMain').css({
'position': 'absolute',
'top': 'auto',
'bottom': '55px'
});
console.log('ABSOLUTE');
}
// This is what removes styling assigned from scrolling, when element gets back to top of page
if ($(document).scrollTop() > $('.main').offset().top + 20 && $(document).scrollTop() + div1.height() < (div2_top + 75) && div1_bottom < div3_bottom && $(window).width() > 900) {
$('.ProductMain').css({
'position': 'fixed',
'top': '60px',
'bottom': 'auto'
}); // restore when you scroll up
console.log('FIXED');
}
// This is what removes styling assigned from scrolling, when element gets back to top of page
if($(document).scrollTop() < $('.main').offset().top && $(document).scrollTop() + window.innerHeight < div2_top || $(window).width() < 900) {
$('.ProductMain').removeAttr('style');
}
}
$(document).scroll(function() {
checkOffset();
});
感谢您的帮助!
最佳答案
这个问题似乎已经有了答案。请在这里尝试这个答案:
关于javascript - 将 div 设置为固定,直到它与其他元素接触并成为绝对元素。向上滚动时不会恢复为固定状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44956361/