js得禁止页面滚动

在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
    }
  }

}

快拿去试试吧

  • 7
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值