javascript 手风琴不会在第一次点击时触发

javascript accordion does not trigger on the very first click

我用 vanilla JS 做了一个手风琴。那里有 99%,但是当您第一次单击手风琴时,它不会激活它。

data-attribute 直到第二次点击才设置为 true

下面是 JS 代码,link 中有一个工作示例。

  // Get the DOM element.
const accordions = Array.from(document.querySelectorAll('.js- 
accordion'));

const handleClick = accordion => () => {
// Here we set the data attribute of the selected accordion.
const selectedState = accordion.dataset.selected;
/**
 * If the selected accordion's data attribute equals true –
 * then we set it to false.
 */
accordion.dataset.selected = (accordion.dataset.selected === 'true') ? 'false' : 'true'; // eslint-disable-line no-param-reassign

// Set variables
const container = accordion.querySelector('.js-accordion__container');
const body = accordion.querySelector('.js-accordion__body');
const unit = 'px';

/**
 * When the state of the accordion is set to true
 * we return the height of the content and
 * and set the collapsible state to true.
 */
if (selectedState === 'true') {
  container.style.height = `${body.offsetHeight + unit}`;
  accordion.setAttribute('aria-expanded', true);
} else {
  container.style.height = null;
  accordion.setAttribute('aria-expanded', false);
 }
};

 // Bind the event listener.
 accordions.map(accordion => accordion.querySelector('.js- 
 accordion__trigger').addEventListener('click', 
 handleClick(accordion)));

CodePen Example:

问题是因为你的selectedState变量是在你更新手风琴的selected属性之前放置的。

您可以尝试将代码放在您更新手风琴上方所选属性的位置 selectedState