需要修改此脚本以关闭其他不活动的元素

时间:2018-11-23 17:13:12

标签: jquery

我在公司的不同部门有三个区域。在页面加载时,第一个页面会自动打开。我需要的是,如果您向下滚动并打开另一个,其他所有都将关闭。有效地一次只允许一个区域打开。

$(document).ready(function() {
  setTimeout(function() {
    $('.team-list-header').first().trigger("click");
  }, 1000);
  $('.team-list-wrapper').hide();
  $('.team-list-header ').on('click', function() {
    var pointer = '#' + $(this).data('view');
    var isActive = $(this).hasClass("tab-active");
    if (isActive) {
      $(pointer).hide();
      $(this).find('a.click').html('Expand<i class="fas fa-plus-circle"></i>');
      $(this).find('h5 > a').html('<i class="fas fa-caret-right"></i>');
      $(this).removeClass("tab-active");
    } else {
      $(pointer).show();
      $(this).find('a.click').html('collapse<i class="fas fa-minus-circle"></i>');
      $(this).find('h5 > a').html('<i class="fas fa-caret-down"></i>');
      $(this).addClass("tab-active");
    }
  });
});

1 个答案:

答案 0 :(得分:0)

$(document).ready(function() {
  $('.team-list-wrapper').hide();
  
  //bind the click on all the headers like before, storing a
  //jQuery object of all the headers
  var $teamListHeaders = $('.team-list-header').on('click', function() {
    //find the header with the active tab, to get the previously selected one
    //filter out the "this" incase the user double clicks the same one
    var activeHeader = $teamListHeaders.not(this).filter('.tab-active');
    
    //if there is an active header that was not the same as "this",
    //toggle it off
    if (activeHeader) toggleTeamList(activeHeader);
    
    //toggle this header off or on
    toggleTeamList(this);
  });

  setTimeout(function() {
    //toggle on the first header after a second
    toggleTeamList($teamListHeaders.first());
  }, 1000);
  
  //refactored the toggle logic to a method that could be used in the
  //multiple places without having to proxy the logic through the DOM
  //by click triggers
  function toggleTeamList(header) {
    var $header = $(header);
    var $pointer = $('#' + $header.data('view'));
    
    if ($header.hasClass("tab-active")) {
      $pointer.hide();
      $header.find('a.click').html('Expand<i class="fas fa-plus-circle"></i>');
      $header.find('h5 > a').html('<i class="fas fa-caret-right"></i>');
      $header.removeClass("tab-active");
    } else {
      $pointer.show();
      $header.find('a.click').html('collapse<i class="fas fa-minus-circle"></i>');
      $header.find('h5 > a').html('<i class="fas fa-caret-down"></i>');
      $header.addClass("tab-active");
    }
  }
});