问题
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?
Here is an example of what I mean:
<details>
<summary>Header</summary>
<div id=anchored>
Should anchor here.
</div>
</details><br style="font-size:100vh;">
<a href="#anchored">To Header</a>
回答1:
The only way I see it could be achieved is by using JS
- 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>
Without jQuery
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>
回答2:
Provided you have ids for each of your details. This will work if you have multiple enclosing each other. A lot of credit to @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 )
);
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>
来源:https://stackoverflow.com/questions/48100490/how-to-anchor-to-target-element-inside-html-details