我有几个具有相同类的按钮可以切换下拉列表,如果用户单击按钮外部的某个位置,则列表将关闭,但如果用户单击具有相同类的另一个按钮,则属于先前单击的按钮的列表将保留打开,如何更改此设置,以便如果用户单击“此”以外的任何其他按钮 - 其他列表将关闭? (我想做的是将 if 条件更改为 if (!event.target.matches this ('.dropdown-btn')) )
<button onclick="myFunction(this)" class="dropdown-btn">
Pirkt tiešsaistē
</button>
<div class="dropdown-list">
...
</div>
/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction(obj) {
obj.classList.toggle("dropdown-btn-active");
}
// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches('.dropdown-btn')) {
var dropdownBtns = document.getElementsByClassName("dropdown-btn");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('dropdown-show')) {
openDropdown.classList.remove('dropdown-show');
}
}
}
所以呢?功能和她启动它(如果不是活动按钮)。
let buttons = document.querySelectorAll('button');
buttons.forEach(el => el.addEventListener('click', e => {
if (!e.target.closest('.dropdown-btn-active')) {
clearBtns();
}
e.target.classList.toggle("dropdown-btn-active");
}));
// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches('.dropdown-btn')) {
clearBtns();
}
}
function clearBtns() {
let dropdownBtns = document.getElementsByClassName("dropdown-btn");
let i;
for (i = 0; i < dropdownBtns.length; i++) {
let openDropdown = dropdownBtns[i];
if (openDropdown.classList.contains('dropdown-btn-active')) {
openDropdown.classList.remove('dropdown-btn-active');
}
}
}
.dropdown-btn-active {
background: #ff0;
}
.dropdown-list {
display: none;
}
.dropdown-btn-active + .dropdown-list {
display: block;
}
<button class="dropdown-btn">
Pirkt tiešsaistē
</button>
<div class="dropdown-list">
First
</div>
<button class="dropdown-btn">
Pirkt tiešsaistē
</button>
<div class="dropdown-list">
Two
</div>