jQuery 下拉菜单通过单击外部关闭 [英] jQuery drop down menu closing by clicking outside

查看:24
本文介绍了jQuery 下拉菜单通过单击外部关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 jQuery 开发一个简单的下拉菜单.当用户按下触发区域时,它将切换下拉区域.我的问题是如何在下拉菜单之外设置点击事件以关闭下拉菜单?

I am developing a simple dropdown menu with jQuery . When a user press on a trigger area, it will toggle the dropdown area. My question is how to have a click event outside of the dropdown menu so that it close the dropdown menu ?

推荐答案

您可以告诉任何在 DOM 上一直冒泡的单击以隐藏下拉列表,以及任何使其到达下拉列表的父级的单击以停止冒泡.

You can tell any click that bubbles all the way up the DOM to hide the dropdown, and any click that makes it to the parent of the dropdown to stop bubbling.

/* Anything that gets to the document
   will hide the dropdown */
$(document).click(function(){
  $("#dropdown").hide();
});

/* Clicks within the dropdown won't make
   it past the dropdown itself */
$("#dropdown").click(function(e){
  e.stopPropagation();
});

演示:http://jsbin.com/umubad/2/edit

这篇关于jQuery 下拉菜单通过单击外部关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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