js 动态设置元素fixed 页面抖动问题?

windows监听滚动事件,滚动满足fixed条件时,元素一直抖动是什么原因?

window.addEventListener('scroll', this.handleTabFix, true)


handleTabFix () {
  let timeOut = null
  clearTimeout(timeOut)
  timeOut = setTimeout(() => {
    let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
    let offsetTop = document.querySelector('#testNavBar') && document.querySelector('#testNavBar').offsetTop + 60
    scrollTop > offsetTop ? this.isFixTab = true : this.isFixTab = false
    // isFixTab为true时,设置元素为fixed
  }, 1000)
}
阅读 351
2 个回答

猜测是你设置某个元素 fixed 之后,页面高度就不够了;然后它就又被解除 fixed,然后页面高度又超了;于是反复。

解决方案,有两个:

  1. position: sticky
  2. 给这个元素套一个壳,固定高度,fixed 之后留着壳撑页面
let timeOut = null;

window.addEventListener('scroll', () => {
  if (timeOut) {
    cancelAnimationFrame(timeOut);
  }
  timeOut = requestAnimationFrame(handleTabFix);
}, true);

function handleTabFix() {
  let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
  let offsetTop = document.querySelector('#testNavBar') && document.querySelector('#testNavBar').offsetTop + 60;
  
  if (scrollTop > offsetTop) {
    if (!document.querySelector('.placeholder')) {
      let placeholder = document.createElement('div');
      placeholder.style.height = '60px'; 
      placeholder.className = 'placeholder';
      document.querySelector('#testNavBar').insertAdjacentElement('beforebegin',    placeholder);
}
this.isFixTab = true;
} else {
if (document.querySelector('.placeholder')) {
document.querySelector('.placeholder').remove();
}
this.isFixTab = false;
}
}

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏