如何创建仅覆盖某个容器的覆盖,而不是整个html页面?

时间:2018-05-21 09:38:44

标签: javascript html html5

我试图创建一个覆盖容器或模式,它只覆盖页面上的某个容器。我有这个。

#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,而不是其他内容。我怎么能这样做?

2 个答案:

答案 0 :(得分:0)

要实现这一目标,您需要这样做 -

//html

<div style="padding:20px; border: 3px solid black;" id="my_main_div">
    <div id="overlay" onclick="off()"></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>

//css

#my_main_div {
  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;
}

// js

function on() {
    document.getElementById("overlay").style.display = "block";
}

function off() {
    document.getElementById("overlay").style.display = "none";
}

答案 1 :(得分:0)

使用亲戚作为职位。

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>

相关问题