如何修改手风琴组件代码实现点击后滚动到视图顶部?
解决手风琴点击时滚动到页面顶部/激活位置的问题
要实现点击手风琴时滚动到页面顶部(或当前激活的手风琴位置),只需在点击事件的处理逻辑中添加滚动相关代码即可,以下是具体修改方案:
方案1:点击后滚动到页面顶部
修改JavaScript代码,在点击事件处理函数末尾添加滚动到顶部的逻辑:
// 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); } }); // 新增:滚动到页面顶部,开启平滑滚动 window.scrollTo({ top: 0, behavior: 'smooth' }); }); }); 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'; }
说明
window.scrollTo({top: 0})直接让页面滚动到顶部;behavior: 'smooth'开启平滑滚动过渡效果,若不需要平滑滚动,可改为window.scrollTo(0, 0)。
方案2:点击后滚动到当前激活的手风琴位置
如果你想让页面滚动到当前点击的手风琴面板位置(而非页面顶部),可替换滚动逻辑为以下代码:
// 替换方案1中的滚动代码为: item.scrollIntoView({ behavior: 'smooth', block: 'start' // 让元素顶部对齐视口顶部 });
说明
item.scrollIntoView()会将当前点击的手风琴元素滚动到浏览器视口内;block: 'start'确保元素顶部与视口顶部对齐,也可设置为center让元素居中显示。
完整代码(以方案1为例)
以下是整合了滚动到顶部逻辑的完整代码:
HTML
<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>
CSS
.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; }
JavaScript
// 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); } }); // 滚动到页面顶部 window.scrollTo({ top: 0, behavior: 'smooth' }); }); }); 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'; }
内容的提问来源于stack exchange,提问作者Abies
相关产品推荐
相关产品推荐

