You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

点击外部链接时自动展开对应区域的首个Accordion

实现外部链接跳转后自动展开对应区域首个Accordion

问题

我已经创建了两个带外部链接的区域,每个区域都包含Accordion组件。目前点击链接可以平滑滚动到对应区域,但需要点击外部链接时自动展开目标区域内的首个Accordion。

当前使用的jQuery代码

$(document).ready(function(){
// Add smooth scrolling to all links
$(".explore-card a").on('click', function(event) {
// Make sure this.hash has a value before overriding default behavior
if (this.hash !== "") {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
});

解决方法

在滚动完成的回调函数中,针对目标区域内的首个Accordion触发展开操作即可,具体写法需匹配你的Accordion实现逻辑,以下是两种常见场景的修改方案:

场景1:Accordion通过点击头部触发展开

若你的Accordion是点击头部元素(如类名为.accordion-header)实现展开,直接在回调里模拟点击首个头部元素:

$(document).ready(function(){
$(".explore-card a").on('click', function(event) {
if (this.hash !== "") {
event.preventDefault();
var hash = this.hash;
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function(){
window.location.hash = hash;
// 触发目标区域内第一个Accordion头部的点击事件
$(hash).find('.accordion-header').first().trigger('click');
});
}
});
});

场景2:Accordion通过添加类控制展开

若你的Accordion是通过给内容容器添加类(如.show)来显示,直接给首个内容容器添加对应类即可:

$(document).ready(function(){
$(".explore-card a").on('click', function(event) {
if (this.hash !== "") {
event.preventDefault();
var hash = this.hash;
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function(){
window.location.hash = hash;
// 给目标区域内第一个Accordion内容容器添加展开类
$(hash).find('.accordion-content').first().addClass('show');
// 若需给头部同步添加活跃类,可追加:
// $(hash).find('.accordion-header').first().addClass('active');
});
}
});
});

注意事项

  • 请将代码中的.accordion-header、.accordion-content替换为你项目中实际使用的类名
  • 若使用第三方Accordion组件(如Bootstrap Collapse),可直接调用组件的展开方法,例如:$(hash).find('.collapse').first().collapse('show')

内容的提问来源于stack exchange,提问作者Adam Pablo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 12:14:59