<分区>
当摘要元素关闭时,它不会滚动到顶部。有什么方法可以让它自动展开吗?
这是我的意思的一个例子:
<details>
<summary>Header</summary>
<div id=anchored>
Should anchor here.
</div>
</details><br style="font-size:100vh;">
<a href="#anchored">To Header</a>
<分区>
当摘要元素关闭时,它不会滚动到顶部。有什么方法可以让它自动展开吗?
<details>
<summary>Header</summary>
<div id=anchored>
Should anchor here.
</div>
</details><br style="font-size:100vh;">
<a href="#anchored">To Header</a>
最佳答案
我认为可以实现的唯一方法是使用 JS
.closest()
details
并单击它的 summary
元素。$("[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>
使用纯 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/