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

点击链接跳转新页后打开Accordion并滚动到指定ID区块如何实现

实现方案

核心逻辑是页面加载完成后读取URL锚点,定位到对应ID的元素后,找到它所属的details父容器并打开,再滚动到目标位置,以下是可直接使用的实现代码:

1. 改造Accordion类

新增锚点处理逻辑,修改后的完整类代码如下:

/** Class representing an accordion component. */
class Accordion {
  /**
   * Create an accordion component
   *
   * Accepts a container element which should contain a list of `details` and
   * `summary` elements
   *
   * @param   {String}  selector  The container element.
   */
  constructor(selector) {
    if (typeof selector !== "string") {
      console.error("Accordion selector must be a string");
      return;
    }
    this._container = document.querySelector(selector);
    this._container.addEventListener('click', (event) => this._toggle(event));
    // 初始化时自动处理锚点逻辑
    this.handleHashAnchor();
  }

  /**
   * Static method to close all `details` elements that are descendants of the
   * passed in container element.
   *
   * @param   {(HTMLElement|HTMLDocument)}  [elem=document]  The container
   */
  static closeAll(elem = document) {
    const opened = elem.querySelectorAll("details[open]");
    for (const elem of opened) {
      elem.removeAttribute("open");
    }
  }

  /**
   * 处理URL锚点:打开对应手风琴并滚动到目标区域
   */
  handleHashAnchor() {
    const hash = window.location.hash;
    if (!hash) return;
    // 匹配锚点对应的目标元素
    const targetEl = document.querySelector(hash);
    if (!targetEl) return;
    // 查找目标元素所属的手风琴容器
    const targetDetails = targetEl.closest('details');
    if (!targetDetails || !this._container.contains(targetDetails)) return;
    // 关闭其他手风琴,打开目标手风琴
    Accordion.closeAll(this._container);
    targetDetails.setAttribute('open', '');
    // 等待DOM渲染完成后滚动,避免高度计算偏差
    requestAnimationFrame(() => {
      targetEl.scrollIntoView({ behavior: 'smooth' });
    });
  }

  /** Private methods */

  /**
   * Toggle the accordion elements
   *
   * @param   {Event}  event  The triggering event object
   */
  _toggle(event) {
    event.preventDefault();
    const details = event.target.closest("details");
    if (details.hasAttribute("open")) {
      details.removeAttribute("open");
    } else {
      Accordion.closeAll(this._container);
      details.toggleAttribute("open");
    }
  }
}

2. 初始化逻辑

不需要修改原有初始化逻辑,假设你的手风琴外层容器选择器为.accordion-container,初始化代码如下即可:

document.addEventListener('DOMContentLoaded', () => {
  new Accordion('.accordion-container');
});

调整说明

  • 如果不需要平滑滚动,将scrollIntoView的参数改为{ behavior: 'auto' }即可
  • 如果手风琴本身有展开动画,可将requestAnimationFrame替换为对应动画时长的setTimeout,保证滚动位置精准
  • 锚点ID需要和页面内目标元素的ID完全匹配,区分大小写

内容的提问来源于stack exchange,提问作者ryan.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 12:54:02