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)
}
回答:
猜测是你设置某个元素 fixed
之后,页面高度就不够了;然后它就又被解除 fixed
,然后页面高度又超了;于是反复。
解决方案,有两个:
- 用
position: sticky
- 给这个元素套一个壳,固定高度,
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;
}
}
以上是 js 动态设置元素fixed 页面抖动问题? 的全部内容, 来源链接: utcz.com/p/934928.html