【问题标题】:css+js: div click (and elements inside it)css+js: div click(和里面的元素)
【发布时间】:2023-03-28 09:30:01
【问题描述】:

我正在尝试构建一个覆盖网页上所有内容的(半透明)叠加层。 类似这样: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 上有一些 clicable 内容。我在下面有这个功能,但是当我点击 里面的元素 时,主覆盖 div JS 将返回 e.id 作为覆盖 div 本身,不是被点击的元素。这样我就无法知道用户真正点击了哪里

function clickHandler(e){ //hide the div overlaySplash

  e = e || event; 

  alert(e.id);
}

底线:
用户点击了 div 内的标签:dsomething();
用户点击了背景(DIV 本身):closeOverlaySplash();

【问题讨论】:

  • 你能分享更多的 html 和 CSS 以便我们用它来回答你吗?我怀疑是 z-index 问题
  • 您必须停止事件冒泡并为叠加层上的项目设置单独的处理程序:stackoverflow.com/questions/5971601/javascript-event-bubbling
  • @BalintBako 在 html 中哪里去冒泡?
  • e.target 不包含触发事件的实际元素对象吗?

标签: javascript css


【解决方案1】:

我认为您不需要完全停止传播,因为它稍后可能会起到某些作用。为了便于使用,创建包含此功能的单独 js 和 css 文件可能是最简单的。

您遇到的问题基本上是事件在当前不需要时冒泡到父级。您可以轻松检查event.target.id 以查看是否单击了父级。有了这个,您可以确保点击了覆盖与内容。

例如:

if (event.target.id == "overlay") { 
    //hide the overlay 
}

JSFiddler

【讨论】:

  • 谢谢!这确实是一件简单的事情,但它IS 很棘手。谢谢大佬!
  • @Azevedo 只是想知道为什么这个答案不被接受。
【解决方案2】:

像这样:

HTML

<div id="overlaySplash" onclick="clickHandler(event);">
    <div id="insideBox" onclick="clickHandlerInner(event);">Inner</div>
</div>

JS

function clickHandler(event) {
    alert("no");
}
function clickHandlerInner(event) {
    if (!event) var event = window.event;
    event.cancelBubble = true; //IE
    if (event.stopPropagation) event.stopPropagation()
    alert("yes")
}

jsFiddle

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-12
    相关资源
    最近更新 更多