使用 JavaScript 或 jQuery 来阻止默认行为并固定页面位置
代码示例:
jQuery:
$(document).on('click', '.accordion-toggle', function (e) {
e.preventDefault();
var $this = $(this);
if ($this.closest('.panel').hasClass('active')) {
$this.closest('.panel').removeClass('active');
} else {
$('.panel.active').removeClass('active');
$this.closest('.panel').addClass('active');
}
});
JavaScript:
const accordionToggles = document.querySelectorAll('.accordion-toggle');
for (let i = 0; i < accordionToggles.length; i++) {
accordionToggles[i].addEventListener('click', function (e) {
e.preventDefault();
const panel = accordionToggles[i].closest('.panel');
if (panel.classList.contains('active')) {
panel.classList.remove('active');
} else {
const activePanel = document.querySelector('.panel.active');
if (activePanel) {
activePanel.classList.remove('active');
}
panel.classList.add('active');
}
});
}
这些代码的作用是阻止默认行为并确保仅当前展开的面板会占据页面位置。