当我的按钮具有旋转类时,我想将表单的显示从none更改为flex
const button = document.querySelector('.expand');
const form = document.querySelector('input-form');
button.addEventListener('click', rotate);
function rotate(e) {
this.classList.toggle('rotate')
if(this.classList.contains(rotate)) {
form.style.display = 'flex';
} else {
form.style.display = 'none';
}
}
我已经制作了一个codepen来试试这个,谢谢:) https://codepen.io/o-sewell/pen/NpzxxR
答案 0 :(得分:1)
为什么不使用CSS来实现这个目标:
.input-form {
display: none; /*** default display ***/
}
.input-form.rotate {
display: flex; /*** will be display: flex when the rotate class is toggled on ***/
}
在附加课程display: flex
之前,表单不会是rotate
。然后,您可以完全删除JS应用的内联样式(form.style.display = 'flex'; form.style.display = 'none';
)
通过我更新的CSS和更清洁的JS,这里有一个小提琴:https://jsfiddle.net/m8eu5yv9/
这是更新后的代码:
const button = document.querySelector('.expand');
const form = document.querySelector('.input-form');
button.addEventListener('click', rotate);
function rotate(e) {
form.classList.toggle('rotate')
}

.input-form {
display: none; /*** default display ***/
}
.input-form.rotate {
display: flex; /*** will be display: flex when the rotate class is toggled on ***/
}

<button class="expand">
Toggle
</button>
<div class="input-form">
<p>Inner content</p>
</div>
&#13;
答案 1 :(得分:0)
您只需切换表单的类。
const button = document.querySelector('.expand');
const form = document.querySelector('.input-form');
button.addEventListener('click', rotate);
function rotate(e) {
this.classList.toggle('rotate')
form.classList.toggle('flex');
}
&#13;
.flex { display: flex }
&#13;