【问题标题】:How to toggle text on/off with a transition?如何通过过渡打开/关闭文本?
【发布时间】:2019-10-16 15:32:44
【问题描述】:

我正在制作一个页面,该页面的文本以可见标题开始不可见。如果单击标题,则文本将显示在下方。我正在添加收尾工作,并希望使文本滑入。 切换由 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>

【问题讨论】:

  • 请用您尝试过的 CSS 过渡更新我为您制作的 sn-p
  • @mplungjan 嘿,我应该在问题中提到。我计算机上代码中的显示已设置为“无”。不幸的是,仍然没有顺利过渡
  • 我没有回答,只是让你成为了你可以做的 sn-p ;) minimal reproducible example - 但请用你的 CSS 更新你的问题,也许是另一个 sn-p。 JS 可以更改类名并触发 css 过渡
  • 对不起!我误解了。修复了 CSS。
  • 使用display: none 无论如何使用transition 都不会顺利工作。

标签: javascript html css


【解决方案1】:

您可以尝试使用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>

【讨论】:

  • 你删除了display: none;.descriptions 吗?
  • 现在运行良好,谢谢!唯一的问题是我有很多这样的网格格式的标题。以前,如果我在上面的行中打开一个标题,它们都会彼此相邻/叠放在一起,然后向下移动,然后在我关闭切换开关时再次返回。有什么办法保存这个?
  • 也许在每个标题周围放置一个&lt;div&gt;&lt;/div&gt; 以保留一个block 上下文元素
  • 嗯.. 刚刚尝试过,不幸的是似乎没有工作。我认为问题在于不透明度,内容仍然“在那里”,只是暂时不可见。所以下面的任何文本或标题仍然会留下空间,因为上面的内容仍然存在。
猜你喜欢
  • 1970-01-01
  • 2019-11-30
  • 1970-01-01
  • 2013-12-02
  • 1970-01-01
  • 1970-01-01
  • 2021-07-03
  • 2023-03-29
  • 1970-01-01
相关资源
最近更新 更多