“un”用jQuery切换div

时间:2012-04-02 23:52:07

标签: jquery

我正在使用jQuery的.toggle方法来创建一个菜单,在单击div时打开和关闭该菜单。这是我的代码:

$(".header").toggle(function() {
        $(this).find(".parent").fadeIn("fast"); 
        $(this).css("background-color","red");         
    }, function() {
        $(this).find(".parent").fadeOut("fast"); 
        $(this).css("background-color","white");    
}); 

$(document).click(function() {
      $('.parent').fadeOut("fast");
     $(".header").css("background-color","white");

});

$(".parent").click(function(event){
    event.stopPropagation(); 
}); 

http://jsfiddle.net/bmcmahen/X9S5C/8/

这很有效,直到我点击弹出菜单的外面关闭它,然后再次尝试再次单击菜单按钮。然后需要双击。我需要做的是从$(document).click函数中取消div上的点击。关于我怎么做的任何想法?

3 个答案:

答案 0 :(得分:0)

您的代码存在问题,您需要点击两次才能再次继续toggle功能。因此,当您单击文档时,您需要在标题上单击两次。

我试图解决你的问题。您可以添加Active类,无论您点击哪个,当您点击文档然后trigger active header。见demo here

只需用此代码替换它就可以了。

$(".header").toggle(function() {
    $(this).addClass('Active').siblings().removeClass('Active');
   $(this).find(".parent").fadeIn("fast"); 
$(this).css("background-color","red");         
}, function() {
   $(this).find(".parent").fadeOut("fast"); 
 $(this).css("background-color","white");    
}); 

$(document).click(function() {
      //$('.parent').fadeOut("fast");
     //$(".header").css("background-color","white");
    $(".header.Active").trigger('click');

});

$(".parent").click(function(event){
   event.stopPropagation(); 
}); 

$("#search").keyup(function(){
var query = $("#search").val(); 
  $("#results").append(query+"<br>"); 

}); 

答案 1 :(得分:0)

$(document).on('click', function() {
    $(".header .parent").not(':hidden').closest('.header').click();   
});

这将关闭所有弹出菜单,而不仅仅是最新打开的菜单。

保留其他所有内容。无需使用.data()或className。

Fiddle

答案 2 :(得分:0)

这是一个非常接近user1193749的实现,但使用jQuery().data()来跟踪偶数/奇数点击:

http://jsfiddle.net/5E6VP/