window.onscroll仅调用单个函数 多侧边Div添加sticky粘性定位失效问题求助
问题原因
- 全局
header变量被重复声明覆盖:先后两次用var header分别获取左右侧边Div,最终header只会保留最后获取的右侧stickDivR元素,所有操作都会作用在这个元素上,左侧Div永远不会被处理 - 全局
sticky变量仅存储了右侧Div的顶部偏移值,没有区分左右两个Div可能不同的初始偏移位置 - 两个滚动处理函数没有独立绑定对应操作的Div,全部共用全局的
header变量,所以不管调用多少次都只会修改右侧Div
修复方案
拆分左右两个Div的独立变量,各自存储对应的DOM元素和初始偏移值,处理函数单独操作对应元素即可,修复后代码如下:
<script> // 分别定义左右侧边栏的独立变量 const headerL = document.getElementById("stickDivL"); const headerR = document.getElementById("stickDivR"); const stickyL = headerL.offsetTop; const stickyR = headerR.offsetTop; window.onscroll = function() { myFunctionR(); myFunctionL(); } function myFunctionL() { const scrollOffset = window.pageYOffset; if (scrollOffset > stickyL) { headerL.classList.add("sticky"); headerL.classList.add("col-xl-3"); headerL.classList.remove("col-xl-12"); } else { headerL.classList.remove("sticky"); headerL.classList.remove("col-xl-3"); headerL.classList.add("col-xl-12"); } }; function myFunctionR() { const scrollOffset = window.pageYOffset; if (scrollOffset > stickyR) { headerR.classList.add("sticky"); headerR.classList.add("col-xl-3"); headerR.classList.remove("col-xl-12"); } else { headerR.classList.remove("sticky"); headerR.classList.remove("col-xl-3"); headerR.classList.add("col-xl-12"); } }; </script>
可选优化
如果后续需要新增更多粘性定位元素,可以把逻辑抽成公共函数,避免重复代码:
function initSticky(elId) { const el = document.getElementById(elId); const offsetTop = el.offsetTop; return () => { const scrollOffset = window.pageYOffset; if (scrollOffset > offsetTop) { el.classList.add("sticky", "col-xl-3"); el.classList.remove("col-xl-12"); } else { el.classList.remove("sticky", "col-xl-3"); el.classList.add("col-xl-12"); } } } const handleStickyL = initSticky('stickDivL'); const handleStickyR = initSticky('stickDivR'); window.onscroll = () => { handleStickyL(); handleStickyR(); }
内容的提问来源于stack exchange,提问作者Dr. firas habbal
相关产品推荐
相关产品推荐

