作者:battleKing
仓库:Github、CodePen
博客:CSDN、掘金
反馈邮箱:amema@foxmail.com
特别声明:原创不易,未经授权不得转载或抄袭,如需转载可联系笔者授权
基本架构 (Vue框架)
<template>
<button @click="open">弹窗</button>
<div v-for="item in messageList">{{ item.body }}</div>
<div class="modal" :style="isOpen?'display: block;':''">
<div class="modal-content">
<div>你找我干什么?</div>
<button class="close" @click="close">关闭弹窗</button>
</div>
</div>
</template>
<script>
export default {
data() {
return {
messageList: {},
isOpen: false
}
},
mounted(){
this.isOpen = false;
fetch('https://jsonplaceholder.typicode.com/posts')
.then((response) => response.json())
.then((json) => this.messageList = json);
},
methods:{
open(){
this.isOpen = !this.isOpen
},
close(){
this.isOpen = !this.isOpen
}
}
}
</script>
<style>
.modal {
display:none;
position:fixed;
z-index:1;
top:0;
left:0;
width:100%;
height:100%;
background:rgba(0,0,0,0.3)
}
.modal-content {
background: #fefefe;
margin: 15% auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
height:20%;
position:relative;
}
.close {
margin: 20px auto;
display: block;
background:blue;
color:white;
}
</style>
1. 禁止滚动条滚动
methods:{
disableScroll(){
document.body.style.overflow = 'hidden'
},
enableScroll(){
document.body.style.overflow = 'auto'
}
},
watch:{
// 监听弹窗,当弹窗出现时,禁止滚动条滚动
isOpen(value){
if(value){
this.disableScroll()
}else{
this.enableScroll()
}
}
}
2. 使窗口宽度不因为滚动条消失而改变
methods:{
disableScroll(){
const scrollBarWidth = window.innerWidth - document.documentElement.clientWidth;
document.body.style.paddingRight = scrollBarWidth + 'px';
document.body.style.overflow = 'hidden';
},
enableScroll(){
document.body.style.paddingRight='0px'
document.body.style.overflow = 'auto'
}
}
3. 退出页面也要恢复滚动条
beforeDestroy(){
this.enableScroll()
}
❤️ 感谢大家
如果本文对你有帮助,就点个赞支持下吧,你的「赞」是我创作的动力。
如果你喜欢这篇文章的话,可以「点赞」 + 「收藏」 + 「转发」 给更多朋友。