【发布时间】:2019-04-20 11:21:08
【问题描述】:
我有一系列 div,单击它们时,会在每个 div 的正下方展开一个 div。单击另一个 div 时,任何先前展开的 div 都将关闭,而单击的 div 下方的 div 会展开。这真的很好用。我的问题是单击已经打开的 div 应该缩小它下面的 div,但事实并非如此。 我的代码基于这个例子...... https://wpbeaches.com/create-expandcollapse-faq-accordion-collapse-click/ 此示例完美运行 - 单击任何 div 会关闭任何其他 div,包括它自己的(如果它已经打开)。 我的代码运行良好,但如果它已经打开,单击一个 div 并不会关闭它下面的 div。
CSS:
/* Style the element that is used to open and close the accordion class */
div.accordion {
background-color: #fff;
color: #444;
cursor: pointer;
padding: 0px;
width: 100%;
text-align: left;
border: none;
outline: none;
transition: 0.4s;
margin-bottom:10px;
opacity: 0.70;
filter: alpha(opacity=70);
}
/* Add a background color to the accordion if it is clicked on (add the .active class with JS), and when you move the mouse over it (hover) */
div.accordion.active, div.accordion:hover {
background: rgb(255,255,255);
background: linear-gradient(90deg, rgba(255,255,255,1) 0%, rgba(232,231,222,1) 50%, rgba(255,255,255,1) 100%);
opacity: 1;
filter: alpha(opacity=100);
}
/* Style the element that is used for the panel class */
div.panel {
padding: 0 18px;
background-color: white;
max-height: 0;
overflow: hidden;
transition: 0.4s ease-in-out;
opacity: 0;
margin-bottom:10px;
}
div.panel.show {
opacity: 1;
max-height: 500px; /* Whatever you like, as long as its more than the height of the content (on all screen sizes) */
}
JAVASCRIPT:
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var acc = document.getElementsByClassName("accordion");
var panel = document.getElementsByClassName('panel');
for (var i = 0; i < acc.length; i++) {
acc[i].onclick = function() {
var setClasses = !this.classList.contains('active');
setClass(acc, 'active', 'remove');
setClass(panel, 'show', 'remove');
if (setClasses) {
this.classList.toggle("active");
this.nextElementSibling.classList.toggle("show");
}
}
}
function setClass(els, className, fnName) {
for (var i = 0; i < els.length; i++) {
els[i].classList[fnName](className);
}
}
});
</script>
HTML:
我的 html 就像上面 wpbeaches.com 示例中的代码一样。
【问题讨论】:
标签: javascript html css