我是编码的新手,我希望在页面底部有这些面板,按下它时打开一些带按钮和东西的菜单,我认为最好的选择是折叠。但在阅读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>
您应该将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/
他们向下打开的原因是因为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