大家好,我是小梅,公众号:「小梅的前端之路」 原创作者。
作为在前端领域不断探索的一员,在此记录开发中遇到的问题,如果你也遇到了相同的问题,希望本文对你有帮助。
在维护一些项目时,时常会遇到使用iframe元素来实现页面的嵌套。子页面有弹框时,遮盖层往往只能遮住子页面所在的iframe窗口,不能遮住整个页面。
想要实现最简单的子页面的弹框遮住整个页面只需要下面几个步骤:
- 把遮罩层写在父页面中
- 子页面点击按钮时,弹框显示,并且触发父页面的方法,将遮罩层显示
- 点击子页面中的关闭弹框按钮,弹框关闭,并且调用父页面的方法,将遮罩层隐藏
- 父页面中的遮罩层的z-index要是负值,并且小于子页面的弹框的z-index,否则将无法点击子页面的弹框
标题弹框效果图如下所示:
具体代码如下:
父页面test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#parDialog {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
overflow: auto;
margin: 0;
background-color: rgba(0,0,0,0.5);
display: none;
z-index: -1;
}
</style>
</head>
<body>
<iframe src="./test1.html" name="qwe" frameborder="0"></iframe>
<div class="el-tree">
我是父页面的元素
</div>
<div id="parDialog"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js"></script>
<script>
function handleDialog() {
// 父页面显示弹框
var parDialog = document.getElementById('parDialog')
parDialog.style.display = 'block'
}
function handleCancelDialog() {
// 父页面关闭弹框
var parDialog = document.getElementById('parDialog')
parDialog.style.display = 'none'
}
</script>
</body>
</html>
子页面test1.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
#sonDialog {
/*float: right;*/
/*position: absolute;*/
/*background-color: #fff9f3;*/
/*width: 200px;*/
/*height: 400px;*/
z-index: 10;
display: none;
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
overflow: auto;
margin: 0;
background-color: #d6d6d6;
}
</style>
</head>
<body>
<div>
<button id="sonBtn">子页面按钮</button>
<div id="sonDialog">
我是子页面的弹框
<button id="sonCancelBtn">弹框消失</button>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js"></script>
<script>
const sonBtn = document.getElementById('sonBtn')
const sonDialog = document.getElementById('sonDialog')
sonBtn.addEventListener('click', function () {
sonDialog.style.display = 'block'
parent.handleDialog()
})
const sonCancelBtn = document.getElementById('sonCancelBtn')
sonCancelBtn.addEventListener('click', function () {
sonDialog.style.display = 'none'
parent.handleCancelDialog()
})
</script>
</body>
</html>
❤️ 欢迎素质三连[点赞 + 收藏 + 评论]
嗨~我是小梅,有兴趣的话可以在微信搜一搜「小梅的前端之路」第一时间接收文章更新通知,一起沟通、学习成长呀。