如何使用 Vanilla JavaScript 显示平滑过渡的 div

How to display a div with a smooth transition with Vanilla JavaScript

我的网站上有一个阅读更多选项来显示一些信息。

目前我的按钮切换方式类似于 on/off 切换 div 的显示 属性。

我希望通过单击按钮平滑地向下展开页面来显示整个 div,我尝试了一些过渡组合,但我没有运气。我知道转换不适用于显示 属性,有什么想法最好只使用 CSS 和一个简单的函数来实现这一点吗?

function seeMore() {
  const text = document.querySelector('#website-info-idea')
  const text2 = document.querySelector('#website-info-technical ')

  if (text.style.display && text2.style.display === 'block') {
    text.style.display = 'none'
    text2.style.display = 'none'

  } else {
    text.style.display = 'block'
    text2.style.display = 'block'

  }
}
#website-info-idea,
#website-info-technical {
  text-align: center;
  display: none;
  transition: all 1s ease;
}
<a onclick="seeMore()" class="btn btn-secondary btn-md btn-custom">About this Website</a>

<div class="col" id="website-info-idea">Idea</div>
<div class="col" id="website-info-technical">Technical</div>

像这样

function seeMore() {
  const text = document.getElementById('website-info-idea')
  const text2 = document.getElementById('website-info-technical')
  text.classList.toggle("show")
  text2.classList.toggle("show")
}
.col {
  transition: opacity 1s ease-out;
  opacity: 0;
  height: 0;
  overflow: hidden;
}

.col.show {
  opacity: 1;
  height: auto;
}
<a onclick="seeMore()" class="btn btn-secondary btn-md btn-custom">About this Website</a>

<div class="col" id="website-info-idea">Idea</div>
<div class="col" id="website-info-technical">Technical</div>

为了使 div 平滑展开,您必须设置最终状态高度 - 而不是“自动” - 并且过渡必须包括高度的变化。

因此:

function seeMore() {
  const text = document.getElementById('website-info-idea')
  const text2 = document.getElementById('website-info-technical')
  text.classList.toggle("show")
  text2.classList.toggle("show")
}
.col {
  opacity: 0;
  height: 0;
  overflow: hidden;
  transition: all 1s ease-in-out;
}

.col.show {
  opacity: 1;
  height: 23px;
  transition: all 1s ease-in-out;
}
<a onclick="seeMore()" class="btn btn-secondary btn-md btn-custom">About this Website</a>

<div class="col" id="website-info-idea">Idea</div>
<div class="col" id="website-info-technical">Technical</div>