如何锚定到 HTML 详细信息中的目标元素

tri*_*587 6 html anchor

当摘要元素关闭时,它只是不会滚动到顶部。有什么办法让它自动扩展或者什么的吗?

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

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

Rok*_*jan 3

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

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

$("[href^='#']").on("click", function() {
  var $targetDIV = $(this.getAttribute("href"));
  if ($targetDIV.is(":hidden")) {
    $targetDIV.closest("details").prop("open", true);
  }
});
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)

没有 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 )
);
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)