开发者

How to disable outside clicks while an element is visible?

开发者 https://www.devze.com 2023-03-12 06:40 出处:网络
I have a div, divDialog, that contains a simple dialog box. It begins life invisible, but at a cert开发者_Go百科ain point I make it visible. The page has several other elements on it (menus, etc.) tha

I have a div, divDialog, that contains a simple dialog box. It begins life invisible, but at a cert开发者_Go百科ain point I make it visible. The page has several other elements on it (menus, etc.) that have event listeners for the click event.

My question is, once divDialog is visible, how can I disable all click events for everything except divDialog? Of course, once divDialog is invisible again, I'd like to restore all listeners to normal behavior.

I read this elegant answer, but it doesn't disable outside clicks, nor is it cross-platform.

I do have a routine that will detect whether a node is an ancestor of another:

function isAncestorOf(ancestor, descendant) {...}

...and that may be necessary in the solution. But I'm having trouble with event listeners, bubbling, capturing, and cross-platform behavior (can't seem to figure it out for IE).

I'm not using jquery on this one; just regular ol' javascript.

Any suggestions?


You should place a transparent, fixed div over the window. That way any clicks on the screen will be that div and not elements underneath it. This is popularly used as the background overlay for a modal dialog. In IE, you'll need to make sure there's a !DOCTYPE declared for position:fixed to work.

div#overlay {
   position:fixed;
   top:0;
   left:0;
   height:100%;
   width:100%;
   z-index:100;
   background-color:#444444;
   opacity:0.5;
   filter:alpha(opacity=50);
}

And you'll need to make sure divDialog has a z-index greater than that of the overlay.


event.preventDefault will stop an event from bubbling up.

0

精彩评论

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