【问题标题】:How to add transition to height when certain class is removed删除某些类时如何向高度添加过渡
【发布时间】:2021-06-29 14:44:08
【问题描述】:
我正在尝试在删除类“约束”时添加过渡
我不明白我已经为 max-height 添加了转换,但它不起作用
const container = document.getElementById('container');
const button = document.getElementById('button');
button.addEventListener('click', ()=> {
container.classList.remove("constraint");
})
.container{
max-height: auto;
background: red;
overflow: hidden;
-webkit-transition: max-height 1s ease-out;
-moz-transition: max-height 1s ease-out;
-o-transition: max-height 1s ease-out;
transition: max-height 1s ease-out;
}
.constraint{
max-height: 100px;
}
h1 {
font-size: 50px;
}
<div id="container" class="container constraint">
<h1>
Hello
</h1>
<h1>
Hello
</h1>
<h1>
Hello
</h1><h1>
Hello
</h1>
</div>
<button id="button">
expand
</button>
当点击展开时,“约束”被移除但没有过渡
【问题讨论】:
-
您需要先指定height 才能转换max-height。也许this post 对你有帮助?
标签:
javascript
html
css
css-transitions
【解决方案1】:
transition 想要max-height 的固定起始值,而不是auto。设置高数就OK了
max-height: 1000px;
const container = document.getElementById('container');
const button = document.getElementById('button');
button.addEventListener('click', ()=> {
container.classList.remove("constraint");
})
.container {
max-height: 1000px;
background: red;
overflow: hidden;
-webkit-transition: max-height 1s ease-out;
-moz-transition: max-height 1s ease-out;
-o-transition: max-height 1s ease-out;
transition: max-height 1s;
}
.container.constraint {
max-height: 100px;
}
h1 {
font-size: 50px;
}
<div id="container" class="container constraint">
<h1>
Hello
</h1>
<h1>
Hello
</h1>
<h1>
Hello
</h1>
<h1>
Hello
</h1>
</div>
<button id="button">
expand
</button>
【解决方案2】:
你可以添加一个样式,而不是删除一个类。
所以你只需要改变这个:
const container = document.getElementById('container');
const button = document.getElementById('button');
button.addEventListener('click', ()=> {
container.classList.remove("constraint");
})
到这里:
const container = document.getElementById('container');
const button = document.getElementById('button');
const constraint = document.querySelector(".constraint"); // Added this
button.addEventListener('click', ()=> {
constraint.style.maxHeight = "1000px"; // Changed this
})
您的完整代码如下:
const container = document.getElementById('container');
const button = document.getElementById('button');
const constraint = document.querySelector(".constraint"); // Added this
button.addEventListener('click', ()=> {
constraint.style.maxHeight = "1000px"; // Changed this
})
.container{
max-height: auto;
background: red;
overflow: hidden;
-webkit-transition: max-height 1s ease-out;
-moz-transition: max-height 1s ease-out;
-o-transition: max-height 1s ease-out;
transition: max-height 1s ease-out;
}
.constraint{
max-height: 100px;
}
h1 {
font-size: 50px;
}
<div id="container" class="container constraint">
<h1>
Hello
</h1>
<h1>
Hello
</h1>
<h1>
Hello
</h1><h1>
Hello
</h1>
</div>
<button id="button">
expand
</button>