提问者:小点点

如何使用普通JavaScript显示具有平滑过渡的div


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

目前,我的按钮像开/关开关一样切换,这是div的显示属性。

我想通过点击按钮平滑地向下扩展页面来显示整个div,我尝试了一些过渡的组合,但是我没有运气。我知道过渡不工作与显示属性,有任何想法如何实现这与最好只是CSS和一个简单的函数?

null

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>

null


共2个答案

匿名用户

像这样的东西

null

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平滑地展开,您必须设置一个最终状态height--而不是“auto”--并且转换必须包括height的更改。

因此:

null

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>