第一种简单的方法:
在弹窗出现时,在 html 上添加 class:
.open-model {
overflow: hidden;
height: 100%;
}
弹窗消失时,再 remove class
代码示例(react):
import React from \'react\'
import {css} from \'glamor\'
css.global(\'.open-model\', {overflow: \'hidden\', height: \'100%\'})
componentDidUpdate() {
const {isShowModel} = this.state
if (document.body && document.body.classList) {
if (isShowModel) {
document
.querySelectorAll(\'html\')
.forEach(node => node.classList.add(\'open-model\'))
} else {
document
.querySelectorAll(\'html\')
.forEach(node => node.classList.remove(\'open-model\'))
}
}
}
不足之处:弹窗消失后,页面会滚动到最顶部
第二种:弹窗蒙层下的页面不能滚动,同时,弹窗消失后,页面仍然停留在原位置,不会滚动到顶部
这就需要在弹窗出现时,保存此时的 scrollTop,即距离顶部的距离,在弹窗消失时,滚动到这个位置
代码示例(react):
const toggleBodyPosition = isFixedPosition => {
const body = window.document.body
if (isFixedPosition) {
const scrollTop =
window.pageYOffset ||
document.documentElement.scrollTop ||
document.body.scrollTop ||
0
body.style.position = \'fixed\'
body.style.top = `-${scrollTop}px`
} else {
body.style.position = \'\'
const top = -parseInt(body.style.top.replace(\'px\', \'\'))
window.scrollTo(0, top)
body.style.top = \'\'
}
}
export default toggleBodyPosition
在弹窗组件中 import toggleBodyPosition
componentWillMount() {
toggleBodyPosition(true)
}
componentWillUnmount() {
toggleBodyPosition(false)
}