开发者

jquery closing overlay on both outer AND inner clicks?

I'm puzzled by something, thought someone here might have insight.

I've built a simple overlay, but it's not working as expected. Here's the css:

开发者_JAVA技巧
    #overlayOuter {
        display: none;
        position: absolute;
        height: 100%;
        width: 100%;
        background: #000;
        z-index: 100;
        }
    #overlayInner {
        position: absolute;
        top: 100px;
        left: 200px;
        width: 600px;
        height: 400px;
        z-index: 101;
        }

The html is simple:

    Blahblahblah!
    <a href="#" onclick="$('#overlayOuter').show();return false;">show overlay</a>
    <div id="overlayOuter">
        <div id="overlayInner">
            Oyeah? Blahblah!
        </div>
    </div>

I then wanted jquery to close the overlay when someone clicked on overlayOuter but not the overlayInner box (so I could include forms and such).

The first jquery I was expecting to work was ...

    $('#overlayOuter').click(function() {
        $('#overlayOuter').fadeOut('fast');
    });

... which works but strangely also closes when clicking overlayInner! Any forms, etc. are now useless!

The following does work as desired ...

    $('#overlayOuter').click(function(e) {
        if ($(e.target).parents('#overlayInner').length==0) {
            $('#overlayOuter').fadeOut('fast');
        }
    });

... but WTF!! Shouldn't the first one work? Isn't the z-index enough to mask overlayInner separate from overlayOuter?


You're nesting the elements, so when you click the inner div, you're still clicking the outer.

you need to separate them like this:

<div id="overlayOuter">
</div>
<div id="overlayInner">
</div>

Not a problem with layout here that way, since you did set the position to absolute anyway

Here's the updated jfiddle from Stack 101s initially built one http://jsfiddle.net/Dapuc/3/


This is due to Javascript event propagation/bubbling. Events that take place on an element will also take place on the elements containers. To avoid this, check that event.target is the element you want, like in this demo: http://jsfiddle.net/WQS3V/


The first one does work :

http://jsfiddle.net/Dapuc/1/


You can add this:

$('#overlayInner').click(function(e) {
  e.stopImmediatePropagation();
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜