提问人:Andy Blinde 提问时间:9/26/2023 更新时间:9/27/2023 访问量:48
如何在 vanilla javascript 的 if 条件中定位此按钮
How to target this button in the if condition in vanilla javascript
问:
我有几个具有相同类的按钮来切换下拉列表,如果用户单击按钮外的某个位置,则列表将关闭,但是如果用户单击具有相同类的另一个按钮,则属于先前单击的按钮的列表将保持打开状态,我该如何更改它,以便如果用户单击“this”以外的任何其他按钮 - 另一个列表关闭?(我想做的是将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');
}
}
}
答:
0赞
Arbery
9/26/2023
#1
获取所有按钮并绑定每个按钮,在其中使用函数清除所有活动类并将活动类添加到当前项目。addEventListener
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>
评论