2015-03-03 74 views
-1

我添加了一个jQuery标签到一个运行良好的网页除了事实之外,没有选项可以关闭一个标签打开后。一个标签始终保持打开。这可能是一个简单的任务,但我对jQuery/JavaScript很陌生。任何帮助将非常感激。非常感谢!这里谈到的代码:jQuery关闭标签点击后,它已被打开

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

+0

您使用任何插件?如果不分享你的HTML也 – 2015-03-03 08:44:47

回答

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