真的卡在 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;
}
最佳答案
尝试
function toggleOpen() {
panels.forEach(function(panel){
if(panel.classList.contains('open')
panel.classList.remove('open');
});
this.classList.toggle('open');
}
关于javascript - 使用 CSS flexbox 面板和 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54341653/