gpt4 book ai didi

javascript - 展开所有详细信息标签

转载 作者:行者123 更新时间:2023-11-29 21:08:04 25 4
gpt4 key购买 nike

任何人都知道是否有办法为使用语义 <details> 的页面创建展开所有链接标签?我设法创建了一个可以自动打开已关闭详细信息的链接:Link to details section that expands details section as well

现在我正在尝试添加一个链接来展开所有 <details> .

我猜你可以用 javascript 做到这一点,但我在这方面很弱。单击启动脚本的链接会产生一些效果,该脚本会在 html 中找到所有“<详细信息并在显示 html 之前插入单词“打开”。不胜感激。

到此为止

<button onclick="openAll()">Expand All</button>

<script>function openAll() {
var x = document.getElementsByTagName("details");
var i;
for (i = 0; i < x.length; i++) {
x[i].setAttribute("open", "true");
}
</script>

以下适用于第一个 <details>标记,但我想我在上面的循环不正确......

<script>
function openAll() {
document.getElementsByTagName("details")[0].setAttribute("open", "true");
}
</script>

下面是我正在测试的虚拟 html

<details>Hello World<summary>summary</summary>lost</details>
<details>another<summary>good night moon</summary>find me</details>

最佳答案

从 JavaScript 切换页面中的所有 details 元素:

// Toggle open all details elements, onload
// Regardless of their initial status
document.body.querySelectorAll('details')
.forEach((e) => {(e.hasAttribute('open')) ?
e.removeAttribute('open') : e.setAttribute('open',true);
console.log(e.hasAttribute('open'))
})
<details> <!-- Initial status: closed -->
<summary>Details</summary>
Something small enough to escape casual notice.
</details>

<details> <!-- Initial status: closed -->
<summary>Details</summary>
Something small enough to escape casual notice.
</details>

<details> <!-- Initial status: closed -->
<summary>Details</summary>
Something small enough to escape casual notice.
</details>


要关闭所有其他 details,当一个打开时(一次只有一个):

document.body.querySelectorAll('summary').forEach((e) => e.addEventListener("click", (e) => {
document.body.querySelectorAll('details').forEach((e) => (e.hasAttribute('open')) ? e.removeAttribute('open') : '')
}))
<details>
<summary>Details</summary>
Something small enough to escape casual notice.
</details>

<details>
<summary>Details</summary>
Something small enough to escape casual notice.
</details>

<details>
<summary>Details</summary>
Something small enough to escape casual notice.
</details>


打开或关闭时,一次切换所有详细信息:

document.body.querySelectorAll('summary').forEach((e) => e.addEventListener("click", (e) => {
e.preventDefault()
document.body.querySelectorAll('details').forEach((e) => (e.hasAttribute('open')) ? e.removeAttribute('open') : e.setAttribute('open', true))
}))
<details>
<summary>Details</summary>
Something small enough to escape casual notice.
</details>

<details>
<summary>Details</summary>
Something small enough to escape casual notice.
</details>

<details>
<summary>Details</summary>
Something small enough to escape casual notice.
</details>

关于javascript - 展开所有详细信息标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43008609/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com