- 打开弹窗时,给body添加class,
body-fixed
.body-fixed {
position: fixed;
width: 100%;
}
弹窗打开时给body添加类body-fixed
这种方法有个弊端,假设在页面滑到底部,打开弹窗,背景会定位到顶部。
- 使用flex
<html>
<style>
html,
body {
width: 100%;
height: 100%;
}
.container {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
}
.main {
flex: 1;
overflow: scroll;
}
.modal {
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
background:rgba(0,0,0,0.5);
display: flex;
justify-content: center;
align-items: center;
}
</style>
<body>
<div class="container">
<div class="main">.....页面主要内容...</div>
<div class="modal">弹框内容</div>
</div>
</body>
</html>
这种方法也有个弊端:由于使用了overflow,导致在移动端时,页面会异常卡顿。
- 打开弹窗时,给body添加
modal-open
类
.modal-open {
overflow-y: hidden;
}
另,react给body加class
openModal = (event) => {
document.body.classList.add('modal-open');
this.setState({ showModal: true });
}
hideModal = (event) => {
document.body.classList.remove('modal-open');
this.setState({ showModal: false });
}