How to disable outside clicks while an element is visible?

人走茶凉 提交于 2019-12-06 14:18:12

问题


I have a div, divDialog, that contains a simple dialog box. It begins life invisible, but at a certain 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?


回答1:


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.




回答2:


event.preventDefault will stop an event from bubbling up.



来源:https://stackoverflow.com/questions/6296447/how-to-disable-outside-clicks-while-an-element-is-visible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!