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

标签 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>

最佳答案

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

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

$("[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>

关于html - 如何锚定到 HTML 详细信息中的目标元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48100490/

相关文章:

html - 所有 CSS 样式都不适用于 anchor 标记

javascript - CSS 从 url 切换 anchor

javascript - 如何使旋转 block 不超出该部分?

html - BeautifulSoup 找不到元素

html - 图片居中,高度或宽度=原图的100%,图片溢出Responsive Divs

javascript - 使用动态 innerHTML 更改处理按钮 mdl-js 样式

javascript - 为多个&lt;input&gt;添加随机id

c# - AngleSharp 点击 div

Java - 向下滚动到 JTextPane 中的特定行

css-背景色:#xxxxxx; not working