简体   繁体   English

jQuery的手风琴亲密

[英]Jquery accordion close

I'm working on creating a mobile accordion nav for a website. 我正在为网站创建移动手风琴导航。 I have a basic accordion set up, the problem I am having is when I open one tab I want the other tabs to automatically close so only one tab can be opened at once. 我已经设置了基本的手风琴,但是我遇到的问题是当我打开一个选项卡时希望其他选项卡自动关闭,因此一次只能打开一个选项卡。 I've tried a few things but I can't get it to work. 我已经尝试了一些方法,但是无法正常工作。 Here is the code - http://codepen.io/anon/pen/OVvZev 这是代码-http://codepen.io/anon/pen/OVvZev

// Dropdown Menu
var dropdown = document.querySelectorAll('.dropdown');
var dropdownArray = Array.prototype.slice.call(dropdown, 0);
dropdownArray.forEach(function (el) {
    var button = el.querySelector('a[data-toggle="dropdown"]'),
        menu = el.querySelector('.dropdown-menu'),
        arrow = button.querySelector('i.icon-arrow');

    button.onclick = function (event) {
        if (!menu.hasClass('show')) {
            menu.classList.add('show');
            menu.classList.remove('hide');
            arrow.classList.add('open');
            arrow.classList.remove('close');
            event.preventDefault();
        } else {
            menu.classList.remove('show');
            menu.classList.add('hide');
            arrow.classList.remove('open');
            arrow.classList.add('close');
            event.preventDefault();
        }
    };
});

Element.prototype.hasClass = function (className) {
    return this.className && new RegExp("(^|\\s)" + className + "(\\s|$)").test(this.className);
};

What's the best way to go about doing this? 这样做的最佳方法是什么?

Here's a solution: http://codepen.io/merlinmason/pen/KpoBRm 这是一个解决方案: http : //codepen.io/merlinmason/pen/KpoBRm

$(".accordian .title").on("click", function () {
  var content = $(this).parent().find(".content");

  if ($(content).hasClass("open")) {
    $(content).slideUp(400).removeClass("open");
  } else {
    $(".content.open").slideUp(400).removeClass("open");
    $(content).slideDown(400).addClass("open");
  }
});

In short - it checks if the accordion is open, if so it closes it, if not it finds all open accordions, closes them and then opens the current one. 简而言之-它检查手风琴是否打开,如果关闭,则将其关闭,如果找不到,则找到所有打开的手风琴,将其关闭,然后打开当前的手风琴。

Key things: - using class "open" to preserve the state - using "this" to reference to accordion currently being actioned 关键事项:-使用“开放”类保存状态-使用“此”引用当前正在操作的手风琴

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

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