【发布时间】:2020-11-13 18:02:19
【问题描述】:
我正在构建一个带有侧边栏的网站,一旦用户滚动到某个点,它就会固定在网站上。此代码运行良好。
我遇到的问题是当用户滚动到页面底部时,侧边栏与页脚重叠。我编写了代码来检测侧边栏的底部何时与包含元素的位置相同 - 当发生这种情况时,我将获取包含元素底部的位置并减去侧边栏元素的高度并使用该数字给出侧边栏是新的“顶部”(同时也将位置更改为“绝对”)。
这就是我遇到问题的地方 - 一旦边栏位于页脚之上,因为用户滚动代码时,被调用的代码会在正常的“固定”位置代码和“绝对”定位代码之间交替,给它这个闪烁效果。
在我的一生中,我无法弄清楚为什么“固定”代码不断被调用。
代码如下:
( function( $ ) {
var sidebar_pos = $('#secondary')[0].getBoundingClientRect();
var pos_top = sidebar_pos.top + window.scrollY; //need this to get the pos of TOP in the browser - NOT the viewport
var main_pos = $('.main-content')[0].getBoundingClientRect();
var main_bottom = main_pos.bottom + window.scrollY;
var stop_pos;
var i = 0;
$(window).scroll(function(event){
var scroll = $(window).scrollTop();
var produce_pos = $('.produce')[0].getBoundingClientRect();
var pos_bottom = produce_pos.bottom + window.scrollY;
//console.log("scroll "+scroll);
//console.log("top " + pos_top);
console.log(main_bottom);
console.log('bottom ' + pos_bottom);
if( scroll >= pos_top){
if ( pos_bottom >= main_bottom ){
//if the sidebar would end up overlapping the footer
if(i == 0){
//only need to set this once, not on every scroll
stop_pos = main_bottom - $('#secondary').height() ;
}
$('#secondary').removeClass('hover').css({
position: 'absolute',
margin:0,
left: sidebar_pos.left,
top: stop_pos
});
i++;
} else {
$('#secondary').addClass('hover').css({
position: 'fixed',
left: sidebar_pos.left,
marginTop: '1.5em',
top: 20
});
setTimeout(() => {
$('*[data-widget="comet"]').addClass('active');
}, 5000);
setTimeout(() => {
$('*[data-widget="produce"]').addClass('active');
}, 7000);
}
} else if( scroll < pos_top && $('#secondary').hasClass('hover') ){ //if user scrolls up past original pos of sidebar, remove effects
$('#secondary').removeClass('hover').css({
position: 'relative',
left: 'auto',
top: 'auto'
});
i = 0;
}
});
}( jQuery ) );
我还有一个正在运行的脚本的代码笔。 https://codepen.io/antlaur00/pen/ExyrgYR
非常感谢任何帮助!谢谢!
【问题讨论】:
标签: javascript jquery