打开后点击jQuery关闭选项卡

时间:2015-03-03 08:42:55

标签: jquery

我在一个网页上添加了一个jQuery选项卡,该网页运行正常,除了在打开选项卡后没有关闭选项卡的选项。一个标签始终保持打开状态这可能是一项简单的任务,但我对jQuery / JavaScript很陌生。任何帮助将非常感激。非常感谢!代码如下:

$(document).ready(function(){
  var animTime = 300,
      clickPolice = false;
  
  $(document).on('touchstart click', '.acc-btn', function(){
    if(!clickPolice){
       clickPolice = true;
      
      var currIndex = $(this).index('.acc-btn'),
          targetHeight = $('.acc-content-inner').eq(currIndex).outerHeight();
   
      $('.acc-btn h1').removeClass('selected');
      $(this).find('h1').addClass('selected');
      
      $('.acc-content').stop().animate({ height: 0 }, animTime);
      $('.acc-content').eq(currIndex).stop().animate({ height: targetHeight }, animTime);

      setTimeout(function(){ clickPolice = false; }, animTime);
    }
    
  });
  
});

1 个答案:

答案 0 :(得分:0)

您可以执行类似

的操作
$(document).ready(function () {
    var animTime = 300,
        clickPolice = false;

    $(document).on('touchstart click', '.acc-btn', function () {
        if (!clickPolice) {
            clickPolice = true;

            var currIndex = $(this).index('.acc-btn'),
                targetHeight = $('.acc-content-inner').eq(currIndex).outerHeight(),
                $h1 = $(this).find('h1'),
                $content = $('.acc-content').eq(currIndex);

            //sinc we want to toggle the class of the current h1 we can call remove on that element
            $('.acc-btn h1').not($h1).removeClass('selected');
            //toggle the class instead of just adding it
            $h1.toggleClass('selected');

            //nect statement will handle the current content element so no need to process it here
            $('.acc-content').not($content).stop().animate({
                height: 0
            }, animTime);
            console.log($content.get(), targetHeight, $h1.hasClass('selected') ? targetHeight : 0)
            $content.stop().animate({
                //based on whether the selected class is present or not set the height
                height: $h1.hasClass('selected') ? targetHeight : 0
            }, animTime);

            setTimeout(function () {
                clickPolice = false;
            }, animTime);
        }

    });

});

演示:Fiddle