如何在过渡时打开/关闭文本?

问题描述 投票:0回答:1

我正在制作一个页面,该页面的开头是不可见的标题。如果单击标题,则文本显示在下面。我要添加画龙点睛的内容,并希望使文本滑入。切换是使用Javascript(而不是jQuery)控制的。理想的情况是仅使用CSS来执行此操作,但可以使用Javascript。下面的HTML内容,使用Javascript控制下面的切换。

[已经尝试了仅CSS解决方案(下面),该方法不起作用;

function view(id) { //this reads the div id variable passed in with each 'onclick' trigger
  var x = document.getElementsByClassName("descriptions"); //this will find all your descriptions MUST HAVE "description" class
  var i;
  for (i = 0; i < x.length; i++) {
    if (x[i].id !== id)
      x[i].style.display = "none"; //this will turn off all your descriptions except current one
  }
  var e = document.getElementById(id); //this will toggle on/off your active description
  if (e.style.display == 'block')
    e.style.display = 'none';
  else
    e.style.display = 'block';
}
.descriptions {
  display: none;
  height: 100;
  transition: height 0.8s;
}
<div class="toggle" id="a" onclick="view('a1');">
  Chocolate cake with Nutella icing
  <div id="a1" class="descriptions">
    How to make a chocolate cake.
  </div>
</div>
javascript html css
1个回答
0
投票

您可以尝试使用opacity,它允许您在CSS中使用transition

function view(id) { //this reads the div id variable passed in with each 'onclick' trigger
  var x = document.getElementsByClassName("descriptions"); //this will find all your descriptions MUST HAVE "description" class
  var i;
  for (i = 0; i < x.length; i++) {
    if (x[i].id !== id)
      x[i].style.opacity = 0; //this will turn off all your descriptions except current one
  }
  var e = document.getElementById(id); //this will toggle on/off your active description
  if (e.style.opacity == 0)
    e.style.opacity = 1;
  else
    e.style.opacity = 0;
}
.descriptions {
  transition: all 0.3s;
  opacity: 0;
  height: 100;
}
<div class="toggle" id="a" onclick="view('a1');">
  Chocolate cake with Nutella icing
  <div id="a1" class="descriptions">
    How to make a chocolate cake.
  </div>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.