插入子项时动画化容器高度

时间:2018-07-12 07:45:34

标签: javascript css

在插入子元素后,我希望容器的高度平滑过渡。

const cont = document.querySelector('.cont')
    
setTimeout(create,1000)
setTimeout(create,2000)
setTimeout(create,3000)

function create(){
  const div = document.createElement('div')
  div.innerHTML = 'some text'
  cont.appendChild(div)
}
.cont {
    border:1px solid red;
    transition: all .09s linear;
}
    
<div class="cont"></div>
    
    
    

1 个答案:

答案 0 :(得分:2)

我会尝试这样的事情:

然后将类应用于要添加的块。

const cont = document.querySelector('.cont')
    
setTimeout(create,1000)
setTimeout(create,2000)
setTimeout(create,3000)

function create(){
  const div = document.createElement('div')
  div.innerHTML = 'some text'
  div.className = 'block'
  cont.appendChild(div)
}
.cont{
  border:1px solid red;
  overflow: hidden;
}

.block {
  animation-name: blockanim;
  animation-duration: 4s;
}

@keyframes blockanim {
    from {max-height: 0px;}
    to {max-height: 200px;}
}
<div class="cont"></div>