折叠面向上打开

时间:2018-08-30 19:45:00

标签: javascript html css collapse

我是编码的新手,我想像页面底部的这些面板一样,当按下它时,它会打开一些带有按钮和内容的菜单,我认为最好的选择是折叠。但是在阅读了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>

2 个答案:

答案 0 :(得分:0)

您应将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/

答案 1 :(得分:0)

它们向下打开的原因是因为html结构和css表示是这种方式,例如:

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

打开<p>后,出现带有文本“ upper one”(在本例中为您的内容)的<button>。 如果您希望它向上打开,则需要在按钮之前(在html中)显示内容(以避免使用其他css样式来再现预期的效果)。

例如:

<ul class="magic-content">
<li>an example list item</li>
<li>another example item</li>
</ul>
<a class="magic-button" href="#">my magic button</a>

要使其工作,然后在js文件中需要类似的东西。出于本示例的目的,我正在使用jquery:

//FILTERS RESET
$('.magic-button').click(function(event) {
event.preventDefault;
    $('.magic-content').toggleClass('on');
});

您的CSS需要具有以下内容:

.magic-content {display:none;}
.magic-content.on {display:block;}

触发类“ on”的触发是内容的显示/隐藏。

另外,您要引用的示例可以在这里找到:

https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_toggle_class_crossbrowser

在他们的示例中,您需要做的所有更改顺序的操作就是更改html元素的顺序:

<div id="myDIV">
This is a DIV element.
</div>
<button onclick="myFunction()">Try it</button>

内容后的按钮。我希望这有帮助。 G

相关问题