2012-10-22 88 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然後刪除它。