当摘要元素关闭时,它就不会滚动到顶部。有没有办法让它自动膨胀什么的?
这里是我的意思的一个例子:
<details>
<summary>Header</summary>
<div id=anchored>
Should anchor here.
</div>
</details><br style="font-size:100vh;">
<a href="#anchored">To Header</a>
发布于 2018-01-04 17:45:44
我认为实现这一目标的唯一途径是通过使用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>
无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>
发布于 2018-01-04 20:13:16
如果您有您的每个详细信息的ids。如果彼此之间有多重包围,这将是可行的。@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
复制相似问题