【问题标题】:Working on CSS flexbox panel and javascript使用 CSS flexbox 面板和 javascript
【发布时间】:2019-01-24 16:09:31
【问题描述】:

真的停留在 JavaScript 的最后一段代码上。基本上,我在一个 Flexbox 中有三个面板。假设如果单击第一个面板,它将打开并出现一个 img 和文本,第二个和第三个面板也是如此。但是,如果我打开第一个面板然后单击第二个面板,则第一个面板仍然保持打开状态,这意味着图像和文本看起来很紧,当第三个面板打开时甚至更紧。我如何告诉浏览器,如果我单击第一个面板打开然后第二个面板然后关闭第一个面板以便第二个面板有空间?

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

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

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

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

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

     // when I have one panel open and I click another panel the one that was open first closes

CSS

         *, *:before, *:after {
  box-sizing: inherit;
}

img {
    width: 40%;
    height: 20%;
}

.panels {
  min-height:100vh;
  overflow: hidden;
  display: flex;    
}

.panel {
  box-shadow:inset 0 0 0 5px rgba(255,255,255,0.1);
  color:white;
  text-align: center;
  align-items:center;
  /* Safari transitionend event.propertyName === flex */
  /* Chrome + FF transitionend event.propertyName === flex-grow */
  transition:
    font-size 0.7s cubic-bezier(0.61,-0.19, 0.7,-0.11),
    flex 0.7s cubic-bezier(0.61,-0.19, 0.7,-0.11),
    background 0.2s;
  font-size: 20px;
  flex: 1;
  justify-content: center;
  display: flex;
  flex-direction: column;
}


/* Flex Children */

.panel > * {
  margin:0;
  transition:transform 0.5s;
  flex: 1 0 auto;
  display: flex;
  justify-content: center;
  align-items: center;
}

.panel > *:first-child {transform: translateY(-100%);}
.panel.open-active > *:first-child {transform: translateY(0);}
.panel > *:last-child {transform: translateY(100%);}  
.panel.open-active > *:last-child {transform: translateY(-20%);}  

.panel p {
  color: black;
}
.panel p:nth-child(2) {
  font-size: 1em;
}

.panel.open {
  flex: 5;
  font-size:30px;
}

【问题讨论】:

标签: javascript css flexbox


【解决方案1】:

试试

function toggleOpen() {
    panels.forEach(function(panel){
    if(panel.classList.contains('open')
       panel.classList.remove('open');
    });
    this.classList.toggle('open');
}

【讨论】:

    【解决方案2】:

    在切换打开功能中,您基本上可以从所有面板中删除 open 类,然后将 open 类添加到单击的面板。

    
     function toggleOpen() {
          panels.forEach(panel => panel.classList.remove('open'));
          this.classList.toggle('open');
        }
    
    

    您可以在此处查看完整代码。 https://codepen.io/vibhanshu/pen/KbQvYX

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-02
      • 1970-01-01
      • 2018-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-29
      相关资源
      最近更新 更多