简体   繁体   English

Firefox和Internet Explorer中的全窗口onClick处理程序

[英]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 : 以下在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 Firefox or Internet Explorer 6, ie the handler does not get invoked. 但是它在Firefox或Internet Explorer 6中不起作用,即不会调用处理程序。 How to make this work in Firefox and Internet Explorer? 如何在Firefox和Internet Explorer中使其工作?

For what it may help, the following works in IE7+, Safari, Firefox and Chrome: 为了可能有所帮助,以下组件可在IE7 +,Safari,Firefox和Chrome中运行:

<body onclick="clearmenus();">

... or "programmatically": ...或“以编程方式”:

document.getElementsByTagName("body")[0].onclick = function(){ clearmenus(); };

jQuery makes this kind of problem very easy to solve in a cross-browser manner. jQuery使这种问题很容易以跨浏览器的方式解决。

Bind an onclick event handler to body that hides the menu and another to the menu element that stops propagation of the event. 将onclick事件处理程序绑定到隐藏菜单的主体,并将另一个绑定到停止事件传播的菜单元素。

不久前,我写了一个脚本来确定是否用JavaScript单击了“外部”元素

A better option for hiding a menu like that would be to use the onblur event. 隐藏这样的菜单的一个更好的选择是使用onblur事件。

<div id="menu-div" onclick="showMenu('menu');" onblur="hideMenu('menu');">
    <ul id="menu">
        <li>Thing1</li>
    </ul>
</div>

Javascript: 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';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM