如何让overflow scroll容器内的div水平居中?解决滚动卡顿问题
滚动时黄色div居中卡顿问题解决

问题描述
我希望通过scroll事件让黄色div在overflow容器内水平居中,但目前滚动时卡顿严重、表现异常,移动端浏览器的情况比PC端更糟。
核心原因
scroll事件触发频率极高(每秒可达数十次甚至上百次),每次触发直接修改DOM样式会导致浏览器频繁进行重排重绘,移动端设备性能有限,这种开销被放大后卡顿更明显。
解决方案
方案一:用CSS原生特性实现(推荐,零JS性能开销)
利用position: sticky结合定位属性,完全不需要监听scroll事件,靠浏览器原生渲染机制实现居中,性能最优。
.yellow-box { position: sticky; left: 50%; transform: translateX(-50%); /* 保留原有宽高、背景色等样式 */ }
注意:确保父容器的
overflow属性设置正确,且sticky定位的元素不会被其他定位元素遮挡。
方案二:优化JS scroll事件处理
如果必须通过JS实现,通过requestAnimationFrame和标记逻辑减少重排次数:
const container = document.querySelector('.overflow-container'); const yellowBox = document.querySelector('.yellow-box'); let isRendering = false; container.addEventListener('scroll', () => { if (!isRendering) { requestAnimationFrame(() => { // 计算居中位置 const scrollOffset = container.scrollLeft; const availableWidth = container.offsetWidth - yellowBox.offsetWidth; yellowBox.style.left = `${scrollOffset + availableWidth / 2}px`; isRendering = false; }); isRendering = true; } });
requestAnimationFrame确保样式更新在浏览器重绘周期内执行,避免频繁触发重排;- 用
isRendering标记防止同一帧内多次执行更新逻辑。
方案三:节流scroll事件
使用节流函数限制scroll事件的执行频率,比如每16ms(对应60帧/秒)执行一次:
function throttle(func, delay = 16) { let lastTime = 0; return function(...args) { const now = Date.now(); if (now - lastTime >= delay) { func.apply(this, args); lastTime = now; } }; } container.addEventListener('scroll', throttle(() => { const scrollOffset = container.scrollLeft; const availableWidth = container.offsetWidth - yellowBox.offsetWidth; yellowBox.style.left = `${scrollOffset + availableWidth / 2}px`; }));
内容的提问来源于stack exchange,提问作者Mocha
相关产品推荐
相关产品推荐

