删除某些类时如何添加到高度的过渡

时间:2021-06-29 14:44:08

标签: javascript html css css-transitions

我正在尝试在移除类“约束”时添加过渡

我不明白我已经添加了 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>

当点击展开时,“约束”被移除但没有过渡

2 个答案:

答案 0 :(得分:0)

您可以添加样式而不是删除类。

所以你只需要改变这个:

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>

答案 1 :(得分:0)

transition 想要 max-height 的固定起始值,而不是 auto。设置高就可以了

 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>