我正在尝试构建一个覆盖网页所有内容的(半透明)叠加层。 类似于:http://www.jankoatwarpspeed.com/use-jquery-to-turn-off-the-lights-while-watching-videos
<div id="overlaySplash" onclick="clickHandler(this)">
<div id="insideBox">
[ label elements here with onclick="dosomething()" ]
</div>
</div>
CSS
#overlaySplash {
position: absolute;
top: 0;
left: 0;
bottom:0;
right:0;
background: rgb(50, 50, 50);
background: rgba(0, 0, 0, .50);
z-index: 50;
}
#insidebox {
position: absolute;
z-index: 100;
left: 15%;
right: 15%;
bottom: 5%;
line-height: 50px;
text-align: left;
}
问题是我没有使用 jquery 并且覆盖 div 将在 int 上有一些可点击的内容。我在下面有这个功能,但是当我点击里面的元素时,主覆盖 div JS 将返回 e.id 作为覆盖 div 本身,不是点击的元素。这样我就无法判断用户真正点击了哪里。
function clickHandler(e){ //hide the div overlaySplash
e = e || event;
alert(e.id);
}
底线:
用户单击了 div 内的标签:dosomething();
用户点击背景(DIV 本身):closeOverlaySplash();
最佳答案
我认为您不需要完全停止传播,因为它以后可能会起到某些作用。为了便于使用,创建包含此功能的单独 js 和 css 文件可能是最简单的。
您遇到的问题基本上是事件在当前不需要时冒泡到父级。您可以轻松检查 event.target.id
以查看是否单击了父项。有了这个,您可以确保点击了叠加层而不是内容。
例如:
if (event.target.id == "overlay") {
//hide the overlay
}
关于javascript - CSS+JS : div click (and elements inside it),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17528645/