首页 > 解决方案 > 显示更多/显示更少 CSS JS 动画不起作用

问题描述

我的网站中有一些文本,我只想在用户单击标题然后文本以动画形式出现时显示,当用户再次单击标题时文本消失。我在下面制作了这段代码,它对“显示更多”非常有用,但由于某种原因它不适用于“显示更少”!

function showMore(resp) {
  if (document.getElementById(resp).style.maxHeight == "400") {
    document.getElementById(resp).style.animation = "showmore 2s ease-in-out reverse";
    document.getElementById(resp).style.maxHeight = "0";
  } else {
    document.getElementById(resp).style.animation = "showmore 2s ease-in-out";
    document.getElementById(resp).style.maxHeight = "400";
  }
}
@keyframes showmore {
  0% {
    opacity: 0;
    max-height: 0;
  }
  100% {
    opacity: 1;
    max-height: 400px;
  }
}

.awr {
  text-align: left;
  margin-left: 10px;
  font-size: 17;
  color: dimgrey;
  max-height: 0;
  overflow: hidden;
}
<div class="question" onclick="showMore('awr1')">
  <h3>How it Works?</h3>
</div>
<div class="awr" id="awr1">
  <p>this is the text that must be hidden.</p>
</div>

谁能帮我?

标签: javascripthtmlcss

解决方案


我用 jQuery 实现,但你可以很容易地转换成 Javascript。

您可以简单地添加一个类并切换它。

function showMore(resp) {
  $("#" + resp).toggleClass("show");
}
.awr {
  text-align: left;
  margin-left: 10px;
  font-size: 17;
  color: dimgrey;
  height: 0px;
  visibility: hidden;
  transition: all 0.3s linear;
  background-color: #F1F1F1;
}

.show {
  visibility: visible;
  height: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="question" onclick="showMore('awr1')">
  <h3>How it Works?</h3>
</div>
<div class="awr" id="awr1">
  <p>this is the text that must be hidden.</p>
</div>


推荐阅读