到达底部页脚时如何停止粘性侧边栏的固定位置

安德鲁

我有一个很长的侧边栏,它固定在某个滚动位置,但是一旦它到达页面底部,它就会与页脚重叠。在这一点上,我想“取消修复”侧边栏,但不要让它跳回来,因为如果我只是删除固定的类,它会跳起来,但如果我再次滚动,它会跳回。我对 javascript 还是很陌生。

const staticSidebar = document.querySelector('.static-sidebar');
const navTop = staticSidebar.offsetTop;
const footerTop = document.querySelector('.footer').offsetTop;
console.log(`Footer top is ${footerTop}`);

function stickyNavigation() {
  if (window.scrollY >= navTop){
    staticSidebar.classList.add('fixed');   
  } else {
    staticSidebar.classList.remove('fixed');
  }
}

window.addEventListener('scroll', stickyNavigation);

代码笔在这里

安德鲁

我按照我想要的方式进行了这项工作,唯一的问题是侧边栏有时会卡在页脚顶部,但总体而言我对此感到满意。我根据侧边栏相对于页脚的位置将顶部位置设置为负数。

function sticky_relocate() {
    const sticky = document.querySelector('#sticky');
    const window_top = window.scrollY;
    const footer_top = document.querySelector('#footer').offsetTop;
    const div_top = document.querySelector('#sticky-anchor').offsetTop;  
    const div_height = document.querySelector('#sticky').offsetHeight;
    var padding = 0;  // tweak here or get from margins etc

    if (window_top + div_height > footer_top - padding){
        let negTop = (window_top + div_height - footer_top + padding) * -1;
        sticky.style.top = negTop + 'px';
    }else if (window_top > div_top) {
        sticky.classList.add('stick');
        sticky.style.top = 0;
    } else {
        sticky.classList.remove('stick');  
    }
}
window.addEventListener('scroll', sticky_relocate);

更新笔

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章