我是 javascript 的初学者,我不知道很多命令。问题是我想显示三个不同的 div 元素位于相同的确切位置,同时单击三个不同的按钮,这意味着每个三个按钮都有自己单独的下拉列表。因此,当我单击打开其他下拉列表时,我检查是否显示其他下拉列表,然后关闭之前打开的下拉列表,以便这两件事不会重叠。这是有效的方法吗? HTML 片段 -
<header class="primary-header">
<div class="big-wrapper">
<div class="first-icon left col-1-3 ">
<img onclick="toggleDropdown("dropOne");" class="cursor-pointer dropbtn " src="assets/images/icon.32x32.user.white.png" alt="menu-nav">
<div id="dropOne" class="dropdown-content big-wrapper">
<a href="#">First Drop menu 1</a>
<a href="#">First Drop menu 2</a>
<a href="#">First Drop menu 3</a>
</div>
</div>
<div class= "second-icon left col-1-3">
<img onclick="toggleDropdown("dropTwo")" class="cursor-pointer dropbtn" src="assets/images/icon.32x32.hearts.white.png">
<div id="dropTwo" class="dropdown-content big-wrapper">
<a href="#">Second Drop menu 1</a>
<a href="#">Second Drop menu 2</a>
<a href="#">Second Dropmenu 3</a>
</div>
</div>
<div class=" third-icon left col-1-3">
<img onclick="toggleDropdown("dropThree")" class="cursor-pointer dropbtn" src="assets/images/icon.32x32.menu.white.png">
<div id="dropThree" class="dropdown-content big-wrapper">
<a href="#">Third Drop menu 1</a>
<a href="#">Third Drop menu 2</a>
<a href="#">Third Drop menu 3</a>
</div>
</div>
<div class="clr"></div>
</div>
</header>
Javascript-
var dropdown1 = document.getElementById("dropOne");
var dropdown2 = document.getElementById("dropTwo");
var dropdown3 = document.getElementById("dropThree");
function toggleDropdown(elementId) {
if(elementId == "dropOne")
{
dropdown1.classList.toggle("show");
if(dropdown2.classList.contains("show"))
{
dropdown2.classList.toggle("show");
}
if(dropdown3.classList.contains("show"))
{
dropdown3.classList.toggle("show");
}
}
else if(elementId == "dropTwo")
{
dropdown2.classList.toggle("show");
if(dropdown1.classList.contains("show"))
{
dropdown1.classList.toggle("show");
}
if(dropdown3.classList.contains("show"))
{
dropdown3.classList.toggle("show");
}
}
else if(elementId == "dropThree")
{
dropdown3.classList.toggle("show");
if(dropdown2.classList.contains("show"))
{
dropdown2.classList.toggle("show");
}
if(dropdown1.classList.contains("show"))
{
dropdown1.classList.toggle("show");
}
}
}
最佳答案
这取决于你对高效的定义。您将无法显着提高性能,因为它可能已经在几毫秒内执行。
但是,您可以通过使用 add
/remove
代替 contain
/toggle
来减少多行代码(如果由于某种原因将 show
类添加到第二个下拉列表中,您的按钮将开始显示或隐藏错误的项目)。您还可以通过循环到 n 数组来编写更通用的函数。这将允许您更轻松地添加按钮和下拉菜单(此代码未经测试,但您会明白的。):
var dropdownArray = [];
dropdownArray.push(document.getElementById("dropOne"));
dropdownArray.push(document.getElementById("dropTwo"));
dropdownArray.push(document.getElementById("dropThree"));
function toggleDropdown(elementId) {
dropdownArray.forEach(function(dropdown){
if(dropdown.id == elementId) {
dropdown.classList.add("show");
} else {
dropdown.classList.remove("show");
}
});
}
关于javascript - 我正在尝试在 javascript 中显示一些隐藏的 div,这是一个好方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37495859/