我创建了一个手风琴,目前一次只能打开一个面板。但是,当我单击它时,我无法让它滚动到面板的手风琴。
我应该如何修改我的代码以单击手风琴跳转到页面视图的顶部?
这是我的代码:
// Select all accordion items
var acc = document.querySelectorAll('.accordion');
// Iterate to add event listeners
acc.forEach(item => {
item.addEventListener('click', function () {
// When it's clicked, loop through all the items
acc.forEach(el => {
// Close any open items
if (el.classList.contains('active')) {
closeAcc(el);
// If it's the one that was clicked and it's closed, open it
} else if (el === item) {
openAcc(el);
}
});
});
});
function closeAcc (el) {
el.classList.remove('active');
el.nextElementSibling.style.maxHeight = null;
};
function openAcc (el) {
el.classList.add('active');
el.nextElementSibling.style.maxHeight = el.nextElementSibling.scrollHeight + 'px';
}
.accordion {
border-top: 1px solid lightgray;
background-color: white;
color: black;
cursor: pointer;
padding: 18px;
width: 100%;
text-align: left;
outline: none;
}
.active, .accordion:hover {
background-color:lightseagreen;
color: black;
}
.active{
font-weight: bold;
text-align: center;
font-size: 1.5rem;
position:sticky;
}
.accordion:after {
content: '\002B';
color: black;
font-weight: bold;
float: right;
}
.active:after {
content: "\2212";
}
.content {
max-height: 0;
transition: max-height 0.2s ease-out;
background-color:white;
color: black;
padding: 0 18px;
overflow: hidden;
}
<button class="accordion">TITLE 1</button>
<div class="content">
<p>details</p>
</div>
<button class="accordion">TITLE 2</button>
<div class="content">
<p>details</p>
</div>
<button class="accordion">TITLE 3</button>
<div class="content">
<p>details</p>
</div>
示例文本,因为我的帖子大部分都是代码......
尝试这样的事情:
<script>
document.addEventListener("DOMContentLoaded", function() {
const panels = document.querySelectorAll(".panel");
panels.forEach(panel => {
panel.addEventListener("click", () => {
// Scroll nach oben
window.scrollTo({
top: 0,
behavior: "smooth" // Optional: Fügt Scroll-Animation hinzu
});
});
});
});
</script>