简体   繁体   English

jQuery 活动元件上的手风琴手风琴

[英]jQuery toggle accordion on active element

I have 4 items.我有 4 个项目。 The first item is active by default.默认情况下,第一项处于活动状态。 When the user selects another item, the accordion should appear beneath that one, the active one.当用户选择另一个项目时,手风琴应该出现在该项目下方,即活动项目下方。 All other accordions should close.所有其他手风琴都应该关闭。

<div class="nav-link acti-show-cone active" id="show-cl1"
     style="display: block; cursor: pointer;">
  <div class="rectangle-cust1"></div>
  <div class="move-text-lf accordion" style="display: inline-block;">
    FIRST ITEM
  </div>
  <div class="panel">
    <p>Lorem ipsum...</p>
  </div>
</div>

<div class="nav-link acti-show-ctwo" id="show-cl2"
     style="display: block; cursor: pointer;">
  <div class="rectangle-cust2"></div>
  <div class="move-text-lf accordion" style="display: inline-block;">
    SECOND ITEM
  </div>

  <div class="panel">
    <p>Lorem ipsum.232323232..</p>
  </div>
</div>

Here is the jQuery:这是 jQuery:

var acc = document.getElementsByClassName('accordion');
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].addEventListener('click', function () {
    /* Toggle between adding and removing the "active" class,
    to highlight the button that controls the panel */
    console.log('ivan', this);
    //this.classList.toggle("active");
    $('.active').not($(this)).removeClass('active');
    $(this).addClass('active');

    /* Toggle between hiding and showing the active panel */
    var panel = this.nextElementSibling;
    if (panel.style.maxHeight) {
      panel.style.maxHeight = null;
    } else {
      panel.style.maxHeight = panel.scrollHeight + 'px';
    }
  });
}

The problem here is that the first active item doesn't show it's panel, when you open a page.这里的问题是,当您打开页面时,第一个活动项目不显示它的面板。

Next bigger problem is the toggle, right now it opens the panel when you click on an item and closes when you click on it again.下一个更大的问题是切换,现在当你点击一个项目时它会打开面板,当你再次点击它时它会关闭。 But it doesn't close back when I click on another item.但是当我单击另一个项目时它不会关闭。 The panel should only appear on the active selected item.该面板应该只出现在活动的选定项目上。

JSFIDDLE , but it doesn't work well: https://jsfiddle.net/gk489ocm/ JSFIDDLE ,但效果不佳: https://jsfiddle.net/gk489ocm/

Where I got the idea from: https://www.w3schools.com/howto/howto_js_accordion.asp Just need the toggle to display on the selected, clicked element.我从哪里得到这个想法: https://www.w3schools.com/howto/howto_js_accordion.asp只需要切换显示在选定的单击元素上。

Here it is a working and more compact jQuery function:这是一个工作更紧凑的 jQuery function:

$('.nav-link').on( "click", function() {
  $('.nav-link').removeClass("active");
  $(this).addClass("active");
  $('.panel').hide();
  $(this).find('.panel').show(); 
});

Fiddle: https://jsfiddle.net/Maro94/tmw7agvz/1/小提琴: https://jsfiddle.net/Maro94/tmw7agvz/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM