展开折叠功能,根据元素高度展开,不需提前计算元素高度

<div>我是title  <a class="a" onclick="expand()">展开</a></div>
  <div id="more" class="moreDiv">
    <p>123123123</p>
    <p>123123123</p>
    <p>123123123</p>
    <p>123123123</p>
    <p>123123123</p>
    <p>123123123</p>
    <p>123123123</p>
  </div>
.moreDiv {
  transition: all .2s;
  max-height: 0px;
  overflow: hidden;
  will-change: max-height;
}

.a {
  color: blue;
  cursor: pointer;
}
var state = 0
function expand() {
  var div = document.getElementById('more');
  var a = document.getElementsByClassName('a');
  if (state == 0) {
    div.style.maxHeight = div.scrollHeight + 'px';
    a[0].innerHTML = '收起';
  } else {
    div.style.maxHeight = '0px';
    a[0].innerHTML = '展开';
  }
  
  state = 1^state
}

 

posted @ 2023-03-15 09:57  abc1234_abc  阅读(42)  评论(0编辑  收藏  举报