gpt4 book ai didi

javascript - Accordion - 隐藏已打开

转载 作者:行者123 更新时间:2023-11-28 02:09:17 25 4
gpt4 key购买 nike

我正在尝试找出一种正确的方法来在单击新标题时隐藏 Accordion 中打开的所有子部分。到目前为止,我已经包含了一个 jsfiddle。只需要一种方法来关闭打开的部分。谢谢!

html

<!DOCTYPE html>
<html>
<title>W3.CSS</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<body>
<div class="w3-container">

<h2>Active Accordions</h2>
<p>In this example we add the w3-red class to an active accordion (when the button is clicked on and the content is opened).</p>

<button onclick="myFunction('Demo1')" class="w3-button w3-block w3-black w3-left-align">Open Section 1</button>
<div id="Demo1" class="w3-hide w3-container">
<p>Some text..</p>
</div>

<button onclick="myFunction('Demo2')" class="w3-button w3-block w3-black w3-left-align">Open Section 2</button>
<div id="Demo2" class="w3-hide w3-container">
<p>Some other text..</p>
</div>

</div>

</body>
</html>

js

function myFunction(id) {
var x = document.getElementById(id);
if (x.className.indexOf("w3-show") == -1) {
x.className += " w3-show";
x.previousElementSibling.className =
x.previousElementSibling.className.replace("w3-black", "w3-red");
} else {
x.className = x.className.replace(" w3-show", "");
x.previousElementSibling.className =
x.previousElementSibling.className.replace("w3-red", "w3-black");
}
}

https://jsfiddle.net/2eda9kz5/1/

最佳答案

您需要使用切换,因为它会显示或隐藏匹配的元素。查看 jQuery 文档:http://api.jquery.com/toggle/

同时检查这个答案!它解释了如何关闭所有其他元素,但不关闭您单击的元素。 JQuery: Toggle Element that is clicked and hide all other

关于javascript - Accordion - 隐藏已打开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48847917/

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