2012-10-22 92 views
1

我有一个导航,我正在使用jQuery幻灯片显示导航下的内容。当你点击不同的导航项时,我得到了div的切换,但是当我点击相同的导航项关闭它时,它会弹出关闭的选项卡,然后再次打开。我现在正在关闭它的div内有一个关闭按钮。Toggeling jQuery隐藏/显示

我如何获得一个div关闭一旦它被打开>

链接到示例here

我jQuery是如下:

(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() { 

      $('.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); 

,我有点火:

$(document).ready(function(){ 

    $('.show_hide').showHide({   
     speed: 300, // speed you want the toggle to happen 
     easing: '', // the animation effect you want. Remove this line if you dont want an effect and if you haven't included jQuery UI 
     changeText: 0, // if you dont want the button text to change, set this to 0 
     showText: 'View',// the button text to show when a div is closed 
     hideText: 'Close' // the button text to show when a div is open 
    }); 

}); 
+0

如何检查单击的项目是否是当前打开的项目(添加/删除类别)或使用is(“:visible”)'。如果它只是隐藏它,否则做另一个向上/向下滑动的东西? –

回答

0

那么,你滑动所有的divs在点击,哪mea当前打开的div也会滑动。

$('.toggleDiv').slideUp(options.speed, options.easing); 

我建议是给打开的div像“IS_OPEN”一类,它删除 当你打开另一格。你可以做任何其他的逻辑之前检查类上点击:

if($(this).hasClass('is_open')) return; 
+0

有人可以创建一个jsfiddle并给我一个工作的例子,我仍然失去 – user1764887

0

只需添加一类这样的伎俩,避免了所有在$(“toggleDiv。”)选择的div额外的操作。

最简单的方法是检查toggleDiv是否可见。只要将'display'属性从none改为block就行了。

使用简单$(this).addClass('opened_div');打开div然后删除它。