jQuery Toggle函数与Mouseup冲突

我正在尝试创建一个下拉菜单,可以使用切换按钮打开和关闭它,也可以通过单击文档本身的任何位置来关闭它。

当某人点击“切换”按钮时,菜单会正常打开。 如果访问者然后单击文档上的任何其他位置,菜单将关闭, 需要2次单击才能再次激活该按钮的切换function。 当然,我想将其减少到1次点击

查看http://jsfiddle.net/MEweN/3/以解决此问题。 有人可以帮帮我吗?

切换将其状态保存在您调用它的对象上。 每次调用Toggle时,它都会在函数1和函数2之间交替。它对您的应用程序一无所知。 它只是在您每次调用它时传递的两个函数之间交替。

当您在不使用Toggle的情况下重置弹出窗口的状态时,它会失去同步,因为它现在不知道您想要返回到第一个状态。 因此,当您再次单击时,它会在您希望它执行第一个函数时执行第二个函数。

解决这个问题的最好方法是使用比Toggle更聪明的东西。 您需要检测弹出窗口是否打开并相应地采取行动,或者存储一些状态是否打开。 您不能使用Toggle,因为它对您的应用程序来说不够智能。

在处理实际代码时,我还发现在文档中处理mouseup事件与处理对象中的click事件并不是很相容。 问题是鼠标在点击之前出现,因此您将按顺序获得两个事件,并且您将无法获得所需的效果。 当我更改为文档中的单击时,它更容易这样:

$("#general_show").click(function () { var $this = $(this); if ($this.hasClass('selected')) { $this.removeClass('selected').parent().next().hide(); } else { $this.addClass('selected').parent().next().show(); } return(false); }); $(document).click(function (e) { if ($('#general_info').is(':visible') && $(e.target).parents('#general_info').length === 0) { $('#general_show').removeClass('selected').parent().next().hide(); return(false); } }); 

工作示例: http : //jsfiddle.net/jfriend00/KTNAq/

  $("#general_show").click(function () { if( $(this).is('.selected') ){ $(this).removeClass().parent().next().hide() }else{ $(this).addClass('selected').parent().next().show() } }); $(document).mouseup(function (e) { if ( $('#general_show').is('.selected') && $(e.target).parents('#general_info').length === 0 && $(e.target).attr('id')!== "general_show" ) { $('#general_show').click() } }); 
 $("#general_show").click(function () { if ( $('#general_info').is(':visible') ){ // Hiding informations $(this).removeClass('selected').parent().next().hide(); // try to always pass argument to removeClass, which class you want to remove } else { // Showin informations $(this).addClass('selected').parent().next().show(); }}); $(document).mouseup(function (e) { // We don't want to use this function when clicked on button if (e.target.id == 'general_show') return; if ( $('#general_info').is(':visible') ){ $('#general_show').removeClass().parent().next().hide(); } }); 

JSFiddle链接: http : //jsfiddle.net/MEweN/5/