0

我在网上找到了这个显示和隐藏 div 的 jQuery 插件。除了一个因素外,它非常适合我的网站。单击标题时,会出现相应的 div。但是在您单击另一个标题之前,该 div 不会消失。如何调整下面的代码,以便再次单击同一标题时,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);
4

3 回答 3

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;

});​
于 2012-06-22T15:02:05.727 回答
0

只需检查 div 的状态并相应地显示/隐藏

http://jsfiddle.net/psLYW/1/

于 2012-06-22T15:01:00.580 回答
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/

于 2012-08-18T15:09:37.727 回答