单击时手风琴滚动到顶部?
Posted
技术标签:
【中文标题】单击时手风琴滚动到顶部?【英文标题】:Accordion scroll to top when clicked? 【发布时间】:2021-06-26 00:17:31 【问题描述】:我有这些可以打开和关闭的手风琴。我还希望手风琴在被点击时滚动到页面顶部。
html:
<button class="accordion"><h2>Title</h></button>
<div class="panel">
<p>some text</p>
</div>
用于打开和关闭手风琴的javascript:
var acc = document.getElementsByClassName("accordion");
var i;
for (i = 0; i < acc.length; i++)
acc[i].addEventListener("click", function()
/* Toggle between adding and removing the "active" class,
to highlight the button that controls the panel */
this.classList.toggle("active");
/* Toggle between hiding and showing the active panel */
var panel = this.nextElementSibling;
if (panel.style.display === "block")
panel.style.display = "none";
else
panel.style.display = "block";
);
我尝试添加Javascript使其滚动到顶部,但它不起作用:
$('button').click(function()
$(this).animate(
scrollTop:0
, 1000);
);
【问题讨论】:
【参考方案1】:所以,我认为你可以改变你的方法。
考虑到您使用的是 jQuery,您的 HTML 可以是这样的:
...
<div class="accordion">
<div class="accordion-header">Your accordion header</div>
<div class="accordion-content">Your Accordion Content</div>
</div>
...
你的 Javascript 像这样:
function scrollToElement($el, time = 500)
$([document.documentElement, document.body]).animate(
scrollTop: $el.offset().top
, time);
function setupAccordion()
$('.accordion .accordion-header').click(function()
let $parent = $(this).parent();
$parent.toggleClass('active');
scrollToElement($parent);
);
$(document).ready(function()
setupAccordion();
);
你的 CSS 是这样的:
.accordion-header
border-bottom:1px solid #ccc;
padding:1em;
cursor:pointer;
font-weight:bold;
.accordion-content
max-height:0;
opacity:0;
visibility:hidden;
transition:all 0.2s ease;
padding:0;
.accordion.active .accordion-content
max-height:500px;
visibility:visible;
opacity:1;
padding:1em;
游乐场:https://jsfiddle.net/m0fbq2j4/
【讨论】:
以上是关于单击时手风琴滚动到顶部?的主要内容,如果未能解决你的问题,请参考以下文章
Bootstrap手风琴,点击时滚动到活动手风琴的顶部,我将如何在嵌套手风琴上实现?
AngularJS / ui-bootstrap 手风琴 - 单击时滚动到活动(打开)手风琴的顶部