在web页面中,经常遇到一些弹窗内部有滚动条,可以滚动,弹窗后面的文档流也可以滚动,两个滚动区域会相互影响,用户体验不太好。
方案一、封装禁止、允许滚动方法
1、弹出弹窗,禁止滚动,并停留在当前位置
const disableScroll = (domId) => { var scrollTopVal = document.documentElement.scrollTop || document.body.scrollTop; // 禁止滑动 const selectId = domId || 'app' const selectDom = document.getElementById(Id) if (selectDom && selectDom.style.position !== 'fixed') { selectDom.style.position = 'fixed' selectDom.style.top = '-' + scrollTopVal + 'px' selectDom.style.width = '100%' selectDom.style.overflow = 'hidden' } }
2、关闭弹窗,恢复滚动,并恢复在停留位置
const enableScroll = (domId) => { /** *取消滑动限制***/ const selectId = domId || 'app' const selectDom = document.getElementById(Id) if (selectDom && selectDom.style.position === 'fixed') { var scrollVal = Math.abs(parseFloat(selectDom.style.top)) selectDom.style.position = '' selectDom.style.overflow = '' selectDom.style.top = '' if (document.body) { document.body.scrollTop = scrollVal } if (document.documentElement) { document.documentElement.scrollTop = scrollVal } } }
快拿去试试吧