javascript - 如何创建仅覆盖某个容器而不是整个 html 页面的叠加层?
问题描述
我正在尝试创建一个覆盖容器或模式,它只覆盖页面上的某个容器。我有这个。
#overlay {
position: fixed;
display: none;
width: 100%;
height: 100%;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0,0,0,0.5);
z-index: 2;
cursor: pointer;
}
</style>
</head>
<body>
<div id="overlay" onclick="off()"></div>
<div style="padding:20px; border: 3px solid black;" id="my_main_div">
<h2>Overlay</h2>
<p>Add an overlay effect to the page content (100% width and height with a black background color with 50% opacity).</p>
<button onclick="on()">Turn on overlay effect</button>
</div>
<script>
function on() {
document.getElementById("overlay").style.display = "block";
}
function off() {
document.getElementById("overlay").style.display = "none";
}
</script>
但是这个覆盖覆盖了所有页面。而我希望它只覆盖而 my_main_div
不是其他任何东西。我怎样才能做到这一点?
解决方案
使用相对作为位置。
function on() {
document.getElementById("overlay").style.display = "block";
}
function off() {
document.getElementById("overlay").style.display = "none";
}
.row {
position: relative;
}
#overlay {
position: absolute;
display: none;
width: 100%;
height: 100%;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0,0,0,0.5);
z-index: 2;
cursor: pointer;
}
<div class="row">
<div id="overlay" onclick="off()"></div>
<div style="padding:20px; border: 3px solid black;" id="my_main_div">
<h2>Overlay</h2>
<p>Add an overlay effect to the page content (100% width and height with a black background color with 50% opacity).</p>
<button onclick="on()">Turn on overlay effect</button>
</div>
</div>
推荐阅读
- r - 在 SQL Server 中用 r 拟合模型
- visual-studio - nuget.org - 如何防止在使用 Update-Package 时下载未列出的包
- javascript - 排序方法不适用于大量元素
- jquery - Jquery 将字符转换为 ASCII 代码以清理 html 元素
- mysql - MySQL:选择具有最后一条记录的 id 的组的计数
- apache-spark - PYSPARK_PYTHON 环境变量是否仅适用于登录用户?
- coq - Coq 中的 Bove-Capretta 方法
- bash - 'docker ps' 输出格式:仅列出正在运行的容器的名称
- c++ - 如何初始化模板类的哨兵节点的值?
- mariadb - MariaDB 和 HAProxy(集群)的连接问题