如何锚定到 HTML 内的目标元素详情

How to anchor to target element inside HTML details

当摘要元素关闭时,它不会滚动到顶部。有什么方法可以让它自动展开吗?

这是我的意思的一个例子:

<details>
  <summary>Header</summary>
  <div id=anchored>
  Should anchor here.
  </div>
</details><br style="font-size:100vh;">
<a href="#anchored">To Header</a>

我认为可以实现的唯一方法是使用 JS

  • 点击锚元素,找到它的目标 DIV,
  • 找到 .closest() details 并单击它的 summary 元素。
  • 仅当 目标DIV 不可见(详细信息已关闭)时才执行上述所有操作。

$("[href^='#']").on("click", function() {
  var $targetDIV = $(this.getAttribute("href"));
  if ($targetDIV.is(":hidden")) {
    $targetDIV.closest("details").prop("open", true);
  }
});
Don't open summary.<br>
Scroll to the bottom of page and click the link.<br>
Summary should open and the page scroll.

<details>
  <summary>Header</summary>
  <div id=anchored>Should anchor here.</div>
</details>

<p style="height:100vh;"></p>
<a href="#anchored">To Header</a>

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

没有jQuery

使用纯 JS (ES6) 看起来像:

const openDetailsIfAnchorHidden = evt => {
  const targetDIV = document.querySelector(evt.target.getAttribute("href"));
  if ( !! targetDIV.offsetHeight || targetDIV.getClientRects().length ) return;
  targetDIV.closest("details").open = true;
}


[...document.querySelectorAll("[href^='#']")].forEach( 
   el => el.addEventListener("click", openDetailsIfAnchorHidden )
);
Don't open summary.<br>
Scroll to the bottom of page and click the link.<br>
Summary should open and the page scroll.

<details>
  <summary>Header</summary>
  <div id=anchored>Should anchor here.</div>
</details>

<p style="height:100vh;"></p>
<a href="#anchored">To Header</a>

前提是您有每个详细信息的 ID。如果您有多个相互包围,这将起作用。非常感谢@Roko C. Buljan

const openDetailsIfAnchorHidden = (evt) => {
  const el = evt.target;
  let details = document.querySelector(el.getAttribute("href"));
  if ( !!details.offsetHeight || details.getClientRects().length ) return;
  while (details != null)
  {
      details = details.closest("details:not(#" + details.id +
      ")");
      if (details == null)
        return;
      const summary = details.querySelector("summary");
      details.setAttribute('open', '');
  }
}


[...document.querySelectorAll("[href^='#']")].forEach( 
   el => el.addEventListener("click", openDetailsIfAnchorHidden )
);
Don't open summary.<br>
Scroll to the bottom of page and click the link.<br>
Summary should open and the page scroll.

<details id=d1>
  <summary>Header</summary>
  <details id=d2><summary>Header 2</summary><div id=anchored>Should anchor here.</div></details>
</details>

<p style="height:100vh;"></p>
<a href="#anchored">To Header</a>