我相信你正在尋找的東西是這樣的:JSFiddle。
我會經歷每一次我做的改變,並且每個陳述也被評論,但作爲一般校長,我改變了你的代碼,使用圍繞每組按鈕/文本的包裝div
,並且我把文本放在裏面一個內在的div
所以它會尊重max-height
。而不是事件處理程序修改其下一個兄弟,這會失敗,例如,如果您的段落單獨包含在p
標記中,而不是使用p
中的br
標記斷行。這也使得使用父類的:hover
僞類實現懸停改變加顏色效果變得微不足道。
所以,如果你改變你的按鈕/文本組:
<button class="accordion">Home</button>
<div class="panel">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>
到:
<div class="panel">
<button class="accordion">Home</button>
<div class="content">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
</div>
</div>
,並更新你的CSS,改變你的panel
類content
(以前開始上線50你的JSFiddle):
.content {
overflow: hidden;
transition: max-height 0.2s ease-out;
padding-left: 50px;
background-color: #f6f6f6;
width: 220px;
font-size: 10px;
max-height: 100px;
}
並使用CSS設置最大高度爲0,非開板
div.panel:not(.opened) > .content {
max-height: 0;
}
然後,您可以設置按鍵的事件偵聽器,並簡單地切換父opened
類:
document.querySelectorAll('.accordion')
.forEach(element => {
element.onclick = function() {
// first, iterate over other open panels and close them...
// note: using Array.from(...) so we can filter the result below.
Array.from(document.querySelectorAll('.panel.opened'))
// ...but skip the clicked panel, which will be dealt with below
// [edit] we filter here so we can close an already-open panel
.filter(panel => panel !== this.parentNode)
.forEach(panel => {
// toggle the 'opened' class, forcing `false`
panel.classList.toggle('opened', false)
// and remove styling that was set on the element itself
panel.querySelector('.content').style.maxHeight = null;
});
// now toggle the clicked panel's 'opened' class and capture its new value
const toggled = this.parentNode.classList.toggle('opened');
// reference the new div.content, inside the button's parent
const content = this.parentNode.querySelector('.content');
// and either fix its max height or unset it, depending on new state
content.style.maxHeight = toggled? `${content.scrollHeight}px` : null;
}
});
最後,如果你想改變上突出「+」色,現在你可以做到這一點使用上的.panel
僞類:hover
:
div.panel:hover > button.accordion:after {
color: red;
}
你爲什麼不使用JS庫如jQuery? –