美文网首页
vue项目 蒙层上有部分滚动,禁止蒙层下的滚动

vue项目 蒙层上有部分滚动,禁止蒙层下的滚动

作者: 八妹sss | 来源:发表于2019-03-22 11:18 被阅读0次

思考过程###

开始的思路只解决禁止蒙层下滚动的问题

当点击弹出蒙层时加入:

document.body.style = 'position:fixed;top:0;height: 100%;width:100%;overflow: hidden;'

当点击隐藏蒙层时:

document.body.style = ''

后来发现: 蒙层下滚动一段距离后弹出蒙层,蒙层下的滚动消失突然回到了顶部,继续解决这个问题

弹出蒙层时记录滚动的距离

this.scrollY = window.scrollY 
// body定位的top就是滚动的距离
document.body.style = `position:fixed;top:-${this.scrollY}px;height:100%;width:100%;overflow: hidden;`

隐藏蒙层时设置滚动距离,值是存储的滚动距离

window.scrollTo(0, this.scrollY)

完整代码

原生开发时:

let bodyEl = document.bodylet ,
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
  }
 }

在vue中的例子


<---显示蒙层--->
<li v-if="kidsInfoField.class_name" @click="handleActionSheet()" class="kids-info-item class">
    <p class="title">{{kidsInfoField.class_name.field_title}}({{kidsInfoField.class_name.is_need | isNeed}})</p>
    <p :style="isIOS? 'font-weight: bolder;': ''" class="text"><span v-if="!kidsInfo.class_name" class="empty">请选择{{kidsInfoField.class_name.field_title}}</span><span v-else>{{kidsInfo.class_name}}</span></p>
</li>
<---蒙层--->
<div v-show="showActionSheet" @click="hideCommonMask($event)" class="class-name-mask">
    <div class="class-name-wrapper">
        <p class="title"><span class="text">请选择</span><span class="close"></span></p>
        <ul class="squad">
            <li :class="currentActionsheetIndex === index ? 'active' : ''" v-for="(item, index) in currentActionsheetList" :key="index" @click="actionsheetSelect(item, index)" class="squad-item">{{item}}</li>
        </ul>
    </div>
 </div>

<script>
    data () {
        return {
            scrollY: 0
        }
    },
    methods: {
        // 点击显示蒙层
        handleActionSheet () {
            // 解决蒙层下的内容滚动的方法(隐藏时去除这些样式)
            this.scrollY = window.scrollY
            document.body.style = `position:fixed;top:-${this.scrollY}px;height: 100%;width:100%;overflow: hidden;`
            this.showActionSheet = true
        },
        // 点击隐藏蒙层
        hideCommonMask (e) {
            let className = e.target.className
            if (className === 'class-name-mask' || className === 'close') {
                document.body.style = ''
                window.scrollTo(0, this.scrollY)
                this.showActionSheet = false
            }
        }
    }
</script>

相关文章

网友评论

      本文标题:vue项目 蒙层上有部分滚动,禁止蒙层下的滚动

      本文链接:https://www.haomeiwen.com/subject/jrdlvqtx.html