单击文档中的任何位置时如何隐藏下拉菜单。 [英] How to hide a dropdown menu when i click anywhere in the document.

查看:105
本文介绍了单击文档中的任何位置时如何隐藏下拉菜单。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

< button id =" dropdown"的onclick = QUOT; showMenu()">菜单< / button>

< div id =" menu">

< ul>
< li> < a href ="#"> item1< / a> < /锂>

< li> < a href ="#"> item2< / a> < /锂>

< li> < a href ="#"> item3< / a> < /立GT;

< li> < a href ="#"> item4< / a> < /锂>

< li> < a href ="#"> item5< / a> < /锂>
< / ul>
< / div>

<button id="dropdown" onclick="showMenu()"> Menu </button> <div id="menu"> <ul> <li> <a href="#">item1</a> </li> <li> <a href="#">item2</a> </li> <li> <a href="#">item3</a> </li> <li> <a href="#">item4</a> </li> <li> <a href="#">item5</a> </li> </ul> </div>

这里是控制下拉列表的javascript代码

here is the javascript code that controls the dropdown

function showMenu(){
var menu = document.document.getElementById('menu');
if(menu.style.display == "none"){
menu.style.display= "block";} else {menu.style.display="none";}
}

此代码工作正常。问题是,如果显示菜单,则用户必须再次单击下拉按钮才能隐藏。我想要  点击文档中的任何位置来隐藏菜单。

帮助!!

This code works fine. The problem is that if the menu is shown, the user must click again in dropdown button to hide. I want  any click anywhere in the document to hide the menu.
Help!!

推荐答案

add < body>上的onclick属性要隐藏菜单的元素,但是你需要更新你的JavaScript以确保当你点击菜单本身它不会隐藏时,你可以通过检查window.event的srcElement来做到这一点,如果它原来是
来自菜单本身不隐藏它
add the onclick attribute on the <body> element to hide the menu, but you will need to update your JavaScript to make sure that when you click on the menu itself it wont hide, you can do that by checking the srcElement of the window.event if it is originally comes from the menu itself don't hide it


这篇关于单击文档中的任何位置时如何隐藏下拉菜单。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆