body { margin: 0; padding: 20px; } .btn { border: none; outline: none; font-size: inherit; border-radius: 4px; padding: 1em; width: 100%; margin: 1em 0; color: #fff; background-color: #ff5777; } .container { position: fixed; top: 0; left: 0; bottom: 0; right: 0; z-index: 1001; display: none; } .layer { position: absolute; top: 0; left: 0; bottom: 0; right: 0; z-index: 1; background-color: rgba(0, 0, 0, .3); } .content { position: absolute; bottom: 0; left: 0; right: 0; height: 50%; z-index: 2; background-color: #f6f6f6; overflow-y: auto; }
const btnNode = document.querySelector('.btn') const containerNode = document.querySelector('.container') const layerNode = document.querySelector('.layer') const contentNode = document.querySelector('.content') let startY = 0 // 记录开始滑动的坐标,用于判断滑动方向 let status = 0 // 0:未开始,1:已开始,2:滑动中 // 打开蒙层 btnNode.addEventListener('click', () => { containerNode.style.display = 'block' }, false) // 蒙层部分始终阻止默认行为 layerNode.addEventListener('touchstart', e => { e.preventDefault() }, false) // 核心部分 contentNode.addEventListener('touchstart', e => { status = 1 startY = e.targetTouches[0].pageY }, false) contentNode.addEventListener('touchmove', e => { // 判定一次就够了 if (status !== 1) return status = 2 let t = e.target || e.srcElement let py = e.targetTouches[0].pageY let ch = t.clientHeight // 内容可视高度 let sh = t.scrollHeight // 内容滚动高度 let st = t.scrollTop // 当前滚动高度 // 已经到头部尽头了还要向上滑动,阻止它 if (st === 0 && startY < py) { e.preventDefault() } // 已经到低部尽头了还要向下滑动,阻止它 if ((st === sh - ch) && startY > py) { e.preventDefault() } }, false) contentNode.addEventListener('touchend', e => { status = 0 }, false)
问题虽然是解决了,但是回头来看,复杂程度和代码量明显增加了一个梯度。
本着简单方便的原则,我们是不是还可以探索其他的方案呢?
既然touch事件判定比较复杂,何不跳出这个框框,另辟蹊径,探索更加合适的方案。
于是,便有了我们的方案三。
方案三
来讲讲我的思路,既然我们要阻止页面滚动,那么何不将其固定在视窗(即position: fixed),这样它就无法滚动了,当蒙层关闭时再释放。
position: fixed应该不用对大家过多介绍了吧,详细的介绍大家可以参考这篇文章:https://www.jb51.net/article/83175.htm
当然还有一些细节要考虑,将页面固定视窗后,内容会回头最顶端,这里我们需要记录一下,同步top值。
示例代码:
let bodyEl = document.body let top = 0 function stopBodyScroll (isFixed) { if (isFixed) { top = window.scrollY bodyEl.style.position = 'fixed' bodyEl.style.top = -top + 'px' } else { bodyEl.style.position = '' bodyEl.style.top = '' window.scrollTo(0, top) // 回到原先的top } }
以上是“web开发之如何禁止弹窗中蒙层底部页面跟随滚动”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注创新互联行业资讯频道!
新闻标题:web开发之如何禁止弹窗中蒙层底部页面跟随滚动
URL标题:http://scpingwu.com/article/gdeiih.html