h5 端页面在弹窗时禁止底部页面滚动,在实现时,我尝试过几种方法。
方法一: @touchmove.stop.prevent
在遮罩层中添加 @touchmove.stop.prevent
可以实现禁止页面滚动,如下:
<div class="dialog-mask" v-if="isDlgShow" @click="closeHandle(2)" @touchmove.stop.prevent>
</div>
缺点
但是这种方法有个问题:弹窗里面内容有滚动条的也会无法滚动。
方法二:prevent touchmove
通过prevent touchmove
阻止触摸滑动事件touchmove
的默认行为,如下:
// 弹窗的事件
openHandle () {
// 在弹窗打开时直接阻止目标元素的滑动事件的默认行为
document.body.addEventListener('touchmove', this.scrollSetup, { passive: false })
// 打开弹窗
this.hideOrShowDlg()
},
closeHandle (type) {
document.body.removeEventListener('touchmove', this.scrollSetup)
// 关闭弹窗
this.hideOrShowDlg()
},
scrollSetup (e) {
e.preventDefault()
e.stopPropagation()
},
hideOrShowDlg(){
this.showDlg = !this.showDlg
}
addEventListener
addEventListener
的第三个参数是 {passive: false}
。
语法格式:passive: Boolean
;
表示 listener
永远不会调用preventDefault()
;如果 listener
仍然调用了这个函数,客户端将会忽略它并抛出一个控制台警告。
缺点
这种方法同样也有个问题:弹窗里面内容有滚动条的也会无法滚动。
方法三:position:fixed
通过 position:fixed
,在弹窗打开时,将目标元素进行固定,在关闭时恢复。
由于定位会改变元素在页面上的位置,所以需要在fixed
前记录元素的位置,取消fixed
之后将元素又滚动到原来的位置。
代码如下所示:
<script>
export default {
name: "",
data () {
return {
showDlg: false
}
},
watch: {
},
created () {
},
mounted () {
},
methods: {
openHandle () {
/** ------------------ 跳出弹窗页面禁止滚动设置开始 ------------------ */
this.preventScoll(true)
/** ------------------ 跳出弹窗页面禁止滚动设置结束 ------------------ */
// 打开弹窗
this.hideOrShowDlg()
},
closeHandle () {
/** ------------------ 关闭弹窗时移除禁止页面滚动设置开始 ------------------ */
this.preventScoll(false)
/** ------------------ 关闭弹窗时移除禁止页面滚动设置结束 ------------------ */
// 关闭弹窗
this.hideOrShowDlg()
},
hideOrShowDlg(){
this.showDlg = !this.showDlg
},
/**
* 阻止背景滚动
* @param Boolean flag [是否阻止背景滚动]
*/
preventScoll (flag) {
if (flag) {
const top = document.documentElement.scrollTop || document.body.scrollTop;
document.body.style.cssText += `
position: fixed;
width: 100vw;
left: 0;
top: ${-top}px;
`
} else {
const top = document.body.style.top;
document.body.style.cssText += `
position: static;
`;
window.scrollTo(0, Math.abs(parseFloat(top)))
}
}
}
}
</script>
这种方法,实现了需求,目前还没发现不足之处。