WesBos JS30第5天Flex面板 - 修改代码以关闭打开的面板,除了单击的面板

时间:2018-01-16 20:52:59

标签: javascript flexbox

我正在做Wes Bos的杰出JS30课程Should I worry about the alignment during pointer casting?我正在做第5天的Flex面板,我想修改他的最终结果,以便在点击新面板时关闭所有打开的面板。

我创建了一个名为removeOpen的函数,但它也关闭了我点击过的函数:(

const panels = document.querySelectorAll('.panel');

function toggleOpen() {
  this.classList.toggle('open');
}

function removeOpen(e) {
  const openPanels = document.querySelectorAll('.open');
  console.log('removeOpen', this.classList);
  console.log('openPanels', openPanels);
  // this works too well, I need to stagger the command so it fires before toggleOpen
  openPanels.forEach(
    openPanel => openPanel.classList.remove('open')
  );
}

function toggleActive(e) {
  if(e.propertyName.includes('flex')) {
    this.classList.toggle('open-active');
  }
}

panels.forEach(panel => panel.addEventListener('click', toggleOpen));
// remove the line below to make it work as per the tutorial
panels.forEach(panel => panel.addEventListener('click', removeOpen));
panels.forEach(panel => panel.addEventListener('transitionend', toggleActive));

这是一个小提琴,https://courses.wesbos.com/account/access/59ee449bd71f462ee56d1ccf/view/194130264注释panels.forEach(panel => panel.addEventListener('click', removeOpen));以使其按照教程工作。

请有人给我看灯!

1 个答案:

答案 0 :(得分:0)

好的,我知道了我只需将removeOpen放在toggleOpen上面。

所以底部的新功能顺序是:

panels.forEach(panel => panel.addEventListener('click', removeOpen));
panels.forEach(panel => panel.addEventListener('click', toggleOpen));
panels.forEach(panel => panel.addEventListener('transitionend', toggleActive));

我惊讶地发现这简直太容易了。它现在唯一没有做的就是关闭当前面板,如果点击,但这对我的需求是可以的。

这是一个更新的小提琴,https://jsfiddle.net/clintongreen/tLf2woac/