我正在尝试在我的网站上实现手风琴块,但在实现构成手风琴块的功能时遇到了问题。我为此遵循了整个 YouTube 教程,所以...
我正在尝试在我的网站上实现一个可折叠面板块,但在实现组成可折叠面板块的功能时遇到了问题。我为此遵循了整个 YouTube 教程,所以不确定为什么它不起作用。我相信问题出在我的 JavaScript 上,也许是 CSS 中的 .active 代码,但我并不完全确定,因为我才刚学 JS 一周。
这是我所遵循的教程的链接,以备不时之需:
https://www.youtube.com/watch?v=dPLHi7tsoFU&t=3s
这是我当前的代码,我还对 JS 代码进行了故障排除,并附加了该代码。这两个代码都没有解决问题。另外,为了以防万一,我还检查了浏览器控制台,那里没有错误。
JS 故障排除代码
const accordionLabels = document.querySelectorAll('.accordion-content .accordion-label');
accordionLabels.forEach(label => {
label.addEventListener('click', function() {
const accordionContent = this.parentElement;
accordionContent.classList.toggle('active');
});
});
JS 原代码
// Accordion Code Starts Here
const accordion = document.getElementsByClassName('accordion-content');
for (i = 0; i<accordion.length; i++) {
accordion[i].addEventListener('click', function() {
this.classList.toggle('active')
})
}
// Accordion Code Ends Here
CSS
/* Styles for Accordian block in left section of body3 */
.accordion-block {
max-width: 500px;
background-color: brown;
}
.accordion-block .accordion-content {
position: relative;
margin: 10px 0px;
background-color: aqua;
}
.accordion-block .accordion-content .accordion-label {
position: relative;
padding: 10px;
padding-left: 0px;
background-color: beige;
cursor: pointer;
}
.accordion-block .accordion-content .accordion-label::before {
background-color: yellow;
content: '+';
position: absolute;
top: 50%;
right: 20px;
transform: translateY(-50%);
font-size: 1.5em;
}
.accordion-block .accordion-content.active .accordion-label::before {
content: '-';
}
.accordion-block .accordion-content .accordion-text {
position: relative;
background-color: aquamarine;
height: 0;
overflow: hidden;
transition: 0.5s;
overflow-y: auto;
}
.accordion-block .accordion-content.active .accordion-text {
height: auto;
padding: 10px;
}
HTML
<div class="accordion-block">
<div class="accordion-content">
<div class="accordion-label">Sneaker Customization</div>
<div class="accordion-text">
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing 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>
<div class="accordion-content">
<div class="accordion-label">Sneaker Restoration</div>
<div class="accordion-text">
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing 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>
<div class="accordion-content">
<div class="accordion-label">Stock Sourcing</div>
<div class="accordion-text">
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing 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>
</div>