vue中禁止页面滚动/滚动事件穿透-弹出蒙版时弹出层下面还可以滚动问题解决

弹出层时,蒙版下还可以滚动页面

移动端

在蒙层所在div上加 @touchmove.prevent

<div class="maskBox" @touchmove.prevent></div>

PC端

弹层显示时调用 stopMove()停止页面滚动 ,弹层消失时调用 Move()开启页面滚动

//停止页面滚动
stopMove(){
  let m = function(e){e.preventDefault();};
  document.body.style.overflow='hidden';
  document.addEventListener("touchmove",m,{ passive:false });//禁止页面滑动
},
//开启页面滚动
Move(){
  let m =function(e){e.preventDefault();};
  document.body.style.overflow='';//出现滚动条
  document.removeEventListener("touchmove",m,{ passive:true });
}

vue封装

directives: {
  fixed: {
	// inserted 被绑定元素插入父节点时调用
	inserted () {
	  let scrollTop = document.body.scrollTop || document.documentElement.scrollTop
	  document.body.style.cssText += 'position:fixed;width:100%;top:-' + scrollTop + 'px;'
	},
	// unbind 指令与元素解绑时调用
	unbind () {
	  let body = document.body
	  body.style.position = ''
	  let top = body.style.top
	  document.body.scrollTop = document.documentElement.scrollTop = -parseInt(top)
	  body.style.top = ''
	}
  }
},

自定义指令使用

<div  v-if="isShowRecordModal" v-fixed>
    ....
    ....
</div>

 该指令的注意点是必须使用v-if开启关闭弹窗,因为该指令依赖于dom的插入和注销,使用v-show是肯定不行的。

 

posted @   JackieDYH  阅读(224)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示