【发布时间】:2018-09-05 10:52:18
【问题描述】:
我正在按照此代码示例found here 使用 css/html/javascript 创建一个可折叠面板:
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: transparent;
color: #444;
cursor: pointer;
width: auto;
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 {
text-decoration: underline;
}
/* Style the collapsible content. Note: hidden by default */
.collapsible-content {
max-height: 0;
padding: 10px;
overflow: hidden;
transition: max-height 0.2s ease-out;
}
/* Style the collapsible content. Note: shown by default */
.collapsible-content-shown-by-default {
max-height: 100%;
padding: 10px;
overflow: hidden;
transition: max-height 0.2s ease-out;
}
<button class="collapsible" id="collapsible-button-0" onclick="toggleCollapsibleSectionWithAnimation.call(this)"><b>Model</b> (show/hide)</button>
<div class="collapsible-content" id="collapsible-section-0">
<h1>
content
</h1>
</div>
此代码有效,默认情况下可折叠部分将被隐藏。
我想反转这个,所以我的面板默认显示,但它应该以完全相同的方式运行,单击可折叠按钮将打开或关闭下面的部分。
不确定如何反转起始变量。当它开始隐藏时,我们需要在内容面板上从 0 的 max-height 开始。在 javascript 中,这被更改为 content.scrollHeight 以打开面板。
这是一个 JSfiddle 示例:https://jsfiddle.net/trbk5vwg/9/
在 JSfiddle 中,如果您在“collapsible-content”和“collapsible-content-shown-by-default”之间交换 div 类,您将看到切换只能以一种方式工作。
我不确定如何在 css 中获得 scrollHeight,因此不确定如何初始化默认显示面板的 maxHeight(100% 不起作用)。
【问题讨论】:
-
能否提供一个jsfiddle
-
jsfiddle.net/trbk5vwg/8 好的,试试这个 JSFiddle,它可以工作:如果你在 collapsible-content-shown-by-default 和 collapsible-content 之间更改内部 div 的类,那么你可以看到它只能以一种方式工作
-
您是否尝试过通过模拟点击来欺骗可折叠设备?
document.getElementById("collapsible-button-0").click() -
好主意,我现在试试,谢谢
-
你可以做这个纯CSS。
标签: javascript html css