我有三个按钮。他们每个人更改横幅部分的背景。我想在单击时对它们设置活动课。我试图获取按钮的数组并对其进行遍历,但是某些操作不起作用。你能告诉我我在做什么错吗?
代码如下:
const banner = document.getElementById('carousel');
const btns = banner.getElementsByClassName('button');
for (const i = 0; i < btns.length; i++) {
btns[i].addEventListener('click', function() {
const current = document.getElementsByClassName('active');
current[0].className = current[0].className.replace('active', '');
this.className += 'active';
})
};
.carousel {
top: 50%;
position: absolute;
}
.carousel .button {
height: 10px;
width: 10px;
border: 2px solid black;
margin: 10px;
border-radius: 9px;
position: relative;
cursor: pointer;
}
.carousel .button .active {
position: absolute;
margin-top: 3px;
margin-left: 3px;
height: 4px;
width: 4px;
border-radius: 5px;
background: #fea100;
}
<div class="carousel" id="carousel">
<div class="button" id="button1">
<div class="active"></div>
</div>
<div class="button" id="button2">
<div></div>
</div>
<div class="button" id="button3">
<div></div>
</div>
</div>
答案 0 :(得分:1)
关键字 this 表示点击的按钮。您应该将
remove()
和add()
删除/添加元素类:
尝试以下方式:
let banner = document.getElementById('carousel');
let btns = banner.getElementsByClassName('button');
for (let i = 0; i < btns.length; i++) {
btns[i].addEventListener('click', function() {
let current = document.getElementsByClassName('active');
current[0].className = current[0].classList.remove('active');
this.querySelector('div').classList.add('active');
})
}
.carousel {
top: 50%;
position: absolute;
}
.carousel .button {
height: 10px;
width: 10px;
border: 2px solid black;
margin: 10px;
border-radius: 9px;
position: relative;
cursor: pointer;
}
.carousel .button .active {
position: absolute;
margin-top: 3px;
margin-left: 3px;
height: 4px;
width: 4px;
border-radius: 5px;
background: #fea100;
}
<div class="carousel" id="carousel">
<div class="button" id="button1">
<div class="active"></div>
</div>
<div class="button" id="button2">
<div></div>
</div>
<div class="button" id="button3">
<div></div>
</div>
</div>
您还可以按照以下方式使用querySelectorAll()
和forEach()
:
let btns = document.querySelectorAll('.button');
let divs = document.querySelectorAll('.button > div');
btns.forEach(function(btn){
btn.addEventListener('click', function() {
document.querySelector('.active').classList.remove('active');
this.firstElementChild.classList.add('active');
});
})
.carousel {
top: 50%;
position: absolute;
}
.carousel .button {
height: 10px;
width: 10px;
border: 2px solid black;
margin: 10px;
border-radius: 9px;
position: relative;
cursor: pointer;
}
.carousel .button .active {
position: absolute;
margin-top: 3px;
margin-left: 3px;
height: 4px;
width: 4px;
border-radius: 5px;
background: #fea100;
}
<div class="carousel" id="carousel">
<div class="button" id="button1">
<div class="active"></div>
</div>
<div class="button" id="button2">
<div></div>
</div>
<div class="button" id="button3">
<div></div>
</div>
</div>