首页 > 解决方案 > 向上打开的折叠边

问题描述

我是编码新手,我希望在页面底部有这样的面板,当按下它会打开一些带有按钮和东西的菜单,我认为最好的选择是 collapside。但是在阅读了 W3schools 教程后,我没有找到任何关于如何让它们向上打开的参考资料。我希望它只是不要移动整个页面而只是打开一个可点击的窗口。如果不是,我想知道要使用哪个其他东西。这是来自 W3schools 的代码

var coll = document.getElementsByClassName("collapsible");
var i;

for (i = 0; i < coll.length; i++) {
coll[i].addEventListener("click", function() {
this.classList.toggle("active");
var content = this.nextElementSibling;
if (content.style.maxHeight){
  content.style.maxHeight = null;
} else {
  content.style.maxHeight = content.scrollHeight + "px";
} 
});
}
.collapsible {
background-color: #777;
color: white;
cursor: pointer;
padding: 18px;
width: 100%;
border: none;
text-align: left;
outline: none;
font-size: 15px;
}

.active, .collapsible:hover {
background-color: #555;
}

.collapsible:after {
content: '\002B';
color: white;
font-weight: bold;
float: right;
margin-left: 5px;
}

.active:after {
content: "\2212";
}

.content {
padding: 0 18px;
max-height: 0;
overflow: hidden;
transition: max-height 0.2s ease-out;
background-color: #f1f1f1;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>

<h2>Animated Collapsibles</h2>

<p>A Collapsible:</p>
<button class="collapsible">Open Collapsible</button>
<div class="content">
<p>upper one (only one is enought).</p>
</div>

<p>Collapsible Set:</p>
<button class="collapsible">Open Section 1</button>
<div class="content">
<p>1.</p>
</div>
<button class="collapsible">Open Section 2</button>
<div class="content">
<p>2.</p>
</div>
<button class="collapsible">Open Section 3</button>
<div class="content">
<p>3.</p>
</div>
</body>
</html>

标签: javascripthtmlcsscollapse

解决方案


您应该将content变量设置previousElementSibling为之前获取元素。

var content = this.previousElementSibling;

然后,像这样交换折叠按钮和内容的顺序:

<div class="content">
      <p>upper one (only one is enought).</p>
</div>
<button class="collapsible">Open Collapsible</button>

JSFiddle:https ://jsfiddle.net/gf72yw8q/


推荐阅读