平滑瞬态的急剧消失 div

Smoothing a sharp disappearing for transient div

我创建了一个框来通过切换按钮在出现和消失之间切换。

问题是:

我不是网络专家。我写的都是我从不同地方得到并组装的东西。请随时修复任何其他 CSS/JS 错误。不过以上问题是我主要找的。

function toggle_elem()
{
    var elem = document.getElementById('elemid');
    if(elem.style.display == 'none')
    {
        elem.style.display = 'block';
        window.setTimeout(function(){
            elem.style.opacity = 1;
            elem.style.transform = 'scale(1)';
            elem.style.height = '100px';
        },0);
    }
    else
    {
        elem.style.transform = 'scale(0)';
        window.setTimeout(function(){
            elem.style.display = 'none';
            elem.style.height = '0';
        }, 300);
    }
}
#elemid {
    border: 1px solid black;
    opacity: 0;
    transform: scale(0);
    transition: height 0.3s, width 0.3s, padding 0.3s, visibility 0.3s, 0.3s ease opacity, opacity 0.3s ease-out, 0.3s ease transform;
}
<div>
<button onclick="toggle_elem()">Toggle</button>
</div>

<div id="elemid" style="display:none">aaaaa</div>

<div>
<button >Next button</button>
</div>

您即将完成消失动画的平滑过渡。 您唯一需要修改的是这个

elem.style.transform = 'scale(0)';
//this is to support the css animation
elem.style.height = '0'; //move your height set outside of `setTimeout`
window.setTimeout(function(){
   //only set `display` none after the animation completed
   elem.style.display = 'none';
}, 300);

完整代码

function toggle_elem() {
  var elem = document.getElementById('elemid');
  if (elem.style.display == 'none') {
    elem.style.display = 'block';
    window.setTimeout(function() {
      elem.style.opacity = 1;
      elem.style.transform = 'scale(1)';
      elem.style.height = '100px';
    }, 0);
  } else {
    elem.style.transform = 'scale(0)';

    elem.style.height = '0';
    window.setTimeout(function() {
      elem.style.display = 'none';
    }, 300);
  }
}
#elemid {
  border: 1px solid black;
  opacity: 0;
  transform: scale(0);
  transition: height 0.3s, width 0.3s, padding 0.3s, visibility 0.3s, 0.3s ease opacity, opacity 0.3s ease-out, 0.3s ease transform;
}
<div>
  <button onclick="toggle_elem()">Toggle</button>
</div>

<div id="elemid" style="display:none">aaaaa</div>

<div>
  <button>Next button</button>
</div>