Javascript默认打开的可折叠CSS过渡在首次单击时不起作用

时间:2019-11-11 14:13:11

标签: javascript html css css-transitions

我试图进行折叠工作,然后我跟随this example。我想拥有其中一些,并且其中一些默认情况下应该处于活动状态。我检查了this question以获得默认的打开可折叠运行状态,但它工作正常,但CSS过渡在第一次尝试时不起作用。

我从上面的问题中派生了jsfiddle,并将其更改为当前的解决方案。我还增加了过渡时间以更好地显示问题。

JSFiddle:https://jsfiddle.net/0q2cko7p/

function toggleCollapsibleSectionWithAnimation() {
    this.classList.toggle("collapsible-active");
    var buttonId = this.id;
    var sectionId = buttonId.replace("button","section");
    var content = document.getElementById(sectionId);
    if (content.style.maxHeight) {
        content.style.maxHeight = null;
    } else {
        content.style.maxHeight = content.scrollHeight + "px";
    }
}
/* Style the button that is used to open and close the collapsible content */
.collapsible {
  background-color: #777;
  color: white;
  padding: 10px;
  cursor: pointer;
  width: 100%;
  border: none;
  text-align: left;
  outline: none;
  font-size: 15px;
}

/* Add a background color to the button if it is clicked on (add the .active class with JS), and when you move the mouse over it (hover) */
.collapsible-active, .collapsible:hover {
  background-color: #444;
}

.collapsible:after {
  content: '\02795'; /* Unicode character for "plus" sign (+) */
  font-size: 13px;
  color: white;
  float: right;
  margin-left: 5px;
}

.collapsible-active:after {
  content: "\2796"; /* Unicode character for "minus" sign (-) */
}

/* Style the collapsible content. Note: hidden by default */
.collapsible-content {
  max-height: 0;
  padding: 10px;
  overflow: hidden;
  transition: max-height 0.5s ease-out;
}
<button	class="collapsible collapsible-active" id="collapsible-button-0" onclick="toggleCollapsibleSectionWithAnimation.call(this)">
    <b>Model</b>
</button>
<div class="collapsible-content" id="collapsible-section-0" style="max-height: 100%">
	<h1>
    Content Text Content Text Content Text Content Text Content Text Content Text Content Text Content Text Content Text
	</h1>
</div>

1 个答案:

答案 0 :(得分:1)

这是因为.collapsible-content元素的最大高度为:100%;您需要将其设置为像素。

如果您想使用可重用的解决方案,建议您使用数据属性(类似于data-expanded="true"之类的脚本来告诉脚本默认情况下扩展了哪些节点。 这里是example

的链接