示例(vue業(yè)務(wù)場(chǎng)景,配合mint-ui)
<template>
<div class="wrap" :class='show?"fix":""' >
<mt-button type="primary" @click.native="handleClick">primary button</mt-button>
<ul>
<li v-for='(item,key) in list' :key='key'>{{item}}</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
show:false,
list:[1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0]
};
},
methods: {
handleClick() {
// 獲取當(dāng)前的滾動(dòng)高度
let scrollTop = document.scrollingElement.scrollTop;
this.$messagebox.alert('操作成功!').then(action => {
if(action==='confirm'){
//使其盒子的刪除fix類名
this.show=false;
//還原body的原來(lái)的滾動(dòng)高度
document.scrollingElement.scrollTop = scrollTop;
}
});
//使其盒子的添加fix類名
this.show=true;
//設(shè)置body的top值為當(dāng)前滑動(dòng)高度(固定遮罩層下的內(nèi)容拂蝎,禁止滑動(dòng))
document.body.style.top = -scrollTop + 'px';
}
},
};
</script>
<style lang="scss" scoped>
.wrap {
&.fix{
position: fixed;
}
}
</style>
講解
主要利用 position: fixed;穴墅,改變其position的值及其body的top值,來(lái)固定底層
- 當(dāng)點(diǎn)擊按鈕温自,遮罩層出現(xiàn)時(shí)玄货,獲取當(dāng)前的滾動(dòng)高度
- 給要禁止滑動(dòng)的底層(示例中的wrap)添加fix類名(即 position: fixed;)
- 設(shè)置body的top值為當(dāng)前滑動(dòng)高度(固定遮罩層下的內(nèi)容,禁止滑動(dòng))
- 當(dāng)遮罩層消失悼泌,刪除fix類名松捉,還原原來(lái)的滾動(dòng)高度