摘要元素关闭时,它不会滚动到顶部。有没有办法让它自动扩展或什么?
<details>
<summary>Header</summary>
<div id=anchored>
Should anchor here.
</div>
</details><br style="font-size:100vh;">
<a href="#anchored">To Header</a>
答案 0 :(得分:3)
我认为可以实现的唯一方法是使用JS
.closest()
details
并点击它的summary
元素。
$("[href^='#']").on("click", function() {
var $targetDIV = $(this.getAttribute("href"));
if ($targetDIV.is(":hidden")) {
$targetDIV.closest("details").prop("open", true);
}
});
&#13;
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>
&#13;
使用纯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 )
);
&#13;
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>
&#13;
答案 1 :(得分:0)
如果您有每个细节的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 )
);
&#13;
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>
&#13;