我正在制作一个有5个部分的手风琴式菜单,每个部分都有一个子菜单。可以通过单击打开和关闭部分。问题是当用户点击新部分时,上一部分保持打开状态。我试图找出一种方法来触发一个部分,当用户点击不同的部分时,该部分会自动关闭,因此只有他们点击的最新部分才会保持打开状态。我的代码如下。
代码已上传到Fiddle https://jsfiddle.net/brianmaddendesign/spacbe9y/
(function() {
var d = document,
accordionToggles = d.querySelectorAll('.js-accordionTrigger'),
setAria,
setAccordionAria,
switchAccordion,
touchSupported = ('ontouchstart' in window),
pointerSupported = ('pointerdown' in window);
skipClickDelay = function(e) {
e.preventDefault();
e.target.click();
}
setAriaAttr = function(el, ariaType, newProperty) {
el.setAttribute(ariaType, newProperty);
};
setAccordionAria = function(el1, el2, expanded) {
switch (expanded) {
case "true":
setAriaAttr(el1, 'aria-expanded', 'true');
setAriaAttr(el2, 'aria-hidden', 'false');
break;
case "false":
setAriaAttr(el1, 'aria-expanded', 'false');
setAriaAttr(el2, 'aria-hidden', 'true');
break;
default:
break;
}
};
//function
switchAccordion = function(e) {
console.log("triggered");
e.preventDefault();
var thisAnswer = e.target.parentNode.nextElementSibling;
var thisQuestion = e.target;
if (thisAnswer.classList.contains('is-collapsed')) {
setAccordionAria(thisQuestion, thisAnswer, 'true');
} else {
setAccordionAria(thisQuestion, thisAnswer, 'false');
}
thisQuestion.classList.toggle('is-collapsed');
thisQuestion.classList.toggle('is-expanded');
thisAnswer.classList.toggle('is-collapsed');
thisAnswer.classList.toggle('is-expanded');
thisAnswer.classList.toggle('animateIn');
};
for (var i = 0, len = accordionToggles.length; i < len; i++) {
if (touchSupported) {
accordionToggles[i].addEventListener('touchstart', skipClickDelay, false);
}
if (pointerSupported) {
accordionToggles[i].addEventListener('pointerdown', skipClickDelay, false);
}
accordionToggles[i].addEventListener('click', switchAccordion, false);
}
})();
答案 0 :(得分:0)
我在fiddle添加了一些代码。希望这是你正在寻找的。 p>
var menuTitle = document.querySelectorAll('.accordion-content'),
menuCont = document.querySelectorAll('.accordion-title'),
i = 0;
while(i < menuTitle.length) {
if(!e.target.classList.contains('is-expanded')) {
menuTitle[i].classList.remove('is-expanded', 'animateIn');
menuTitle[i].classList.add('is-collapsed');
menuCont[i].classList.remove('is-expanded', 'is-collapsed');
};
i++;
};
单击菜单项时,它会检查是否展开了任何菜单元素,并在运行代码之前关闭该元素。