2012-06-22 78 views
0

我發現這個jQuery插件在線顯示和隱藏div。除了一個因素外,它對我的​​網站來說非常完美。當你點擊標題時,會出現相應的div。但是,除非您點擊另一個標題,否則該div不會消失。我如何調整下面的代碼,以便如果第二次點擊同一個標題,div再次隱藏?調整jQuery函數來隱藏div第二次點擊它?

(function ($) { 
$.fn.showHide = function (options) { 

//default vars for the plugin 
    var defaults = { 
     speed: 1000, 
     easing: '', 
     changeText: 0, 
     showText: 'Show', 
     hideText: 'Hide' 

    }; 
    var options = $.extend(defaults, options); 

    $(this).click(function() { 
// optionally add the class .toggleDiv to each div you want to automatically close 
        $('.toggleDiv').slideUp(options.speed, options.easing); 
     // this var stores which button you've clicked 
     var toggleClick = $(this); 
     // this reads the rel attribute of the button to determine which div id to toggle 
     var toggleDiv = $(this).attr('rel'); 
     // here we toggle show/hide the correct div at the right speed and using which easing effect 
     $(toggleDiv).slideToggle(options.speed, options.easing, function() { 
     // this only fires once the animation is completed 
     if(options.changeText==1){ 
     $(toggleDiv).is(":visible") ? toggleClick.text(options.hideText) : toggleClick.text(options.showText); 
     } 
      }); 

     return false; 

    }); 

}; 
})(jQuery); 

回答

1

試試這個:

$(this).click(function() { 
    var toggleClick = $(this); 
    var toggleDiv = $(this).attr('rel'); 
    var isDivVisible = $(toggleDiv).is(":visible"); 
    $('.toggleDiv').slideUp(options.speed, options.easing); 

    if (!isDivVisible) { 
     $(toggleDiv).slideToggle(options.speed, options.easing, function() { 
      if (options.changeText == 1) { 
       $(toggleDiv).is(":visible") ? toggleClick.text(options.hideText) : toggleClick.text(options.showText); 
      } 
     }); 
    } 
    return false; 

});​ 
0

從我可以告訴,你想只將元素的狀態從可見狀態切換到隱藏狀態(並返回)?

如果你只是想只顯示/隱藏,jQuery的精彩.slideToggle()方法可能會有所幫助。

// Your elements. Change these! 
var link = $('.yourLink'); 
var target = $('.yourDiv'); 

// Showing/hiding 
link.click(function() { 
    target.toggleSlide(); 
    return false; 
}); 

如果沒有,那麼你將要使用的toggle功能,具有兩個自定義的回調,這樣的:

// Your elements. Change these! 
var link = $('.yourLink'); 
var target = $('.yourDiv'); 

link.toggle(function() { 
    // Animate showing 
    !target.is(':animated') && target.slideDown().text('how do you do?'); 
    return false; // stop the default link functionality 
}, function() { 
    // Animate hiding 
    !target.is(':animated') && target.slideUp().text('see you later, alligator'); 
    return false; 
}); 

鏈接: http://api.jquery.com/toggle/ http://api.jquery.com/的slideToggle/