如何在HTML详细信息内定位到目标元素 [英] How to anchor to target element inside HTML details
本文介绍了如何在HTML详细信息内定位到目标元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当summary元素关闭时,它只是不会滚动到顶部.有什么方法可以使其自动展开吗?
When the summary element is closed, it just doesn't scroll to the top. Is there any way of making it auto-expand or something?
<details>
<summary>Header</summary>
<div id=anchored>
Should anchor here.
</div>
</details><br style="font-size:100vh;">
<a href="#anchored">To Header</a>
推荐答案
我认为可以实现的唯一方法是使用JS
The only way I see it could be achieved is by using JS
- 单击锚点元素,找到它的目标DIV,
- 而不是找到
.closest()
details
并单击它的summary
元素. - 仅当 targetDIV 不可见(细节已关闭)时,才执行上述所有操作.
- On an anchor element click, find it's target DIV,
- than find a
.closest()
details
and click it'ssummary
element. - Do all the above only if targetDIV is not visible (details is closed).
$("[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),它看起来像:
Using pure JS (ES6) it would look like:
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详细信息内定位到目标元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文