点击外面的jquery下拉菜单关闭 [英] jquery drop down menu closing by clicking outside

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

问题描述

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

解决方案

你可以告诉任何点击,一直浮起来的DOM隐藏下拉列表,任何点击,使其成为下拉列表的父母停止冒泡。

  / *获取到文档
的任何东西将隐藏下拉列表* /
$(document).click(function(){
$(#dropdown)。 hide();
});

/ *下拉菜单中的点击不会使
通过下拉列表本身* /
$(#dropdown)。click(function(e){
e.stopPropagation();
});

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


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 ?

解决方案

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();
});

Demo: http://jsbin.com/umubad/2/edit

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

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