有没有办法进一步简化这个javascript函数?必须为下拉菜单输入4个变量似乎有点荒谬,当我想要有超过1个按钮时很难跟踪变量。
以下是代码:
<!DOCTYPE html>
<html>
<head>
<style>
.dropbtn:hover, .dropbtn:focus {
background-color: #3e8e41;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
}
.dropdown-content a {
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown a:hover {background-color: #f1f1f1}
.show {display:block;}
</style>
</head>
<body>
<h2>Clickable Dropdown</h2>
<p>Click on the button to open the dropdown menu.</p>
<div class="dropdown">
<button onclick="myFunction('dropdown-content','myDropdown','show','.dropbtn')" class="dropbtn">Dropdown</button>
<div id="myDropdown" class="dropdown-content">
<a href="#home">Home</a>
<a href="#about">About</a>
<a href="#contact">Contact</a>
</div>
</div>
<script>
/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction(dropDownClass,dropDownId,show,dropbtnClass) {
var dropdowns = document.getElementsByClassName(dropDownClass);
var i;
var openDropdown = dropdowns[i];
document.getElementById(dropDownId).classList.toggle(show);
// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches(dropbtnClass)) {
for (i = 0; i < dropdowns.length; i++) {
if (openDropdown.classList.contains(show)) {
openDropdown.classList.remove(show);
}
}
}
}
}
</script>
</body>
</html>
答案 0 :(得分:2)
你的意思是
window.onload=function() {
var btns = document.querySelectorAll(".dropbtn");
for (var i=0;i<btns.length;i++) {
btns[i].onclick=function() {
document.getElementById(this.getAttribute("data-drop")).classList.toggle("show");
}
}
}
.dropbtn:hover,
.dropbtn:focus {
background-color: #3e8e41;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
}
.dropdown-content a {
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown a:hover {
background-color: #f1f1f1
}
.show {
display: block;
}
<h2>Clickable Dropdown</h2>
<p>Click on the button to open the dropdown menu.</p>
<div class="dropdown">
<button data-drop="myDropdown1" class="dropbtn">Dropdown</button>
<div id="myDropdown1" class="dropdown-content">
<a href="#home">Home 1</a>
<a href="#about">About 1</a>
<a href="#contact">Contact 1</a>
</div>
<button data-drop="myDropdown2" class="dropbtn">Dropdown</button>
<div id="myDropdown2" class="dropdown-content">
<a href="#home">Home 2</a>
<a href="#about">About 2</a>
<a href="#contact">Contact 2</a>
</div>
</div>