Full window onClick handler in Firefox and Internet Explorer
I would like an event handler to fire whenever someone clicks anywhere on a window (so I can clear away a menu if they click someplace other than the menu). The following works in Safari:
function checkwho(ev) {
obj=(window.external) ? event.srcElement : ev.target;
var type=obj.nodeName;
if ((type == 'BODY') || (type == 'HTML') || (type == 'DIV')) clearmenus();
}
self.onclick=checkwho;
But it does not work in Firef开发者_高级运维ox or Internet Explorer 6, i.e. the handler does not get invoked. How to make this work in Firefox and Internet Explorer?
jQuery makes this kind of problem very easy to solve in a cross-browser manner.
Bind an onclick event handler to body that hides the menu and another to the menu element that stops propagation of the event.
For what it may help, the following works in IE7+, Safari, Firefox and Chrome:
<body onclick="clearmenus();">
... or "programmatically":
document.getElementsByTagName("body")[0].onclick = function(){ clearmenus(); };
I wrote a script some time ago to Determine if any "Outside" Element was Clicked with JavaScript.
A better option for hiding a menu like that would be to use the onblur
event.
<div id="menu-div" onclick="showMenu('menu');" onblur="hideMenu('menu');">
<ul id="menu">
<li>Thing1</li>
</ul>
</div>
Javascript:
function showMenu(id)
{
var me = document.getElementById(id);
me.style.display = 'block';
}
function hideMenu(id)
{
var me = document.getElementById(id);
me.style.display = 'none';
}
精彩评论