思考過程###
開始的思路只解決禁止蒙層下滾動的問題
當點擊彈出蒙層時加入:
document.body.style = 'position:fixed;top:0;height: 100%;width:100%;overflow: hidden;'
當點擊隱藏蒙層時:
document.body.style = ''
后來發(fā)現(xiàn): 蒙層下滾動一段距離后彈出蒙層,蒙層下的滾動消失突然回到了頂部,繼續(xù)解決這個問題
彈出蒙層時記錄滾動的距離
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)
完整代碼
原生開發(fā)時:
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 () {
// 解決蒙層下的內(nèi)容滾動的方法(隱藏時去除這些樣式)
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>