我需要你的帮助!这是某种类型的图片库:)当我单击它时,我想在面板上添加这个.active类。有人能教我如何用传统函数做到这一点吗?它只对一个元素起作用:(
var panels = document.querySelectorAll(".panel");
console.log(panels);
for (var i = 0; i < panels.length; i++) {
panels[i].addEventListener("click", function() {
var panelClassName = this.className;
addClass(panelClassName);
});
}
function addClass(currentPanel) {
var activePanel = document.querySelector("." + currentPanel);
activePanel.classList.add("active");
}<div class="container">
<div class="panel" style="background-image: url(https://cdn.pixabay.com/photo/2017/02/01/22/02/mountain-landscape-2031539_1280.jpg)">
<h3>Explore the world</h3>
</div>
<div class="panel" style="background-image: url(https://cdn.pixabay.com/photo/2016/11/14/04/45/elephant-1822636_1280.jpg)">
<h3>Elephant</h3>
</div>
<div class="panel" style="background-image: url(https://cdn.pixabay.com/photo/2018/01/14/23/12/nature-3082832_1280.jpg)">
<h3>Lake</h3>
</div>
<div class="panel" style="background-image: url(https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg)">
<h3>Jungle</h3>
</div>
<div class="panel" style="background-image: url(https://cdn.pixabay.com/photo/2015/09/09/16/05/forest-931706_1280.jpg)">
<h3>Forest</h3>
</div>
</div>
发布于 2021-04-11 07:11:26
主要的方法是在将active类添加到单击事件目标之前,有一个函数将该类从所有活动面板中移除。你可以在这里查看代码:
https://jsfiddle.net/p8sr453o/6/
function removeActiveClass() {
const div = document.querySelector('.panel.active');
div && div.classList.remove('active');
}
function addActiveClass(target) {
target.classList.add("active");
}
function addClass(event) {
removeActiveClass();
addActiveClass(event.currentTarget);
}
var panels = document.querySelectorAll(".panel");
console.log(panels);
for (var panel of panels) {
panel.addEventListener("click", addClass);
}.panel {
color: lightblue;
}
.panel.active {
color: red;
}<div class="container">
<div class="panel" style="background-image: url(https://cdn.pixabay.com/photo/2017/02/01/22/02/mountain-landscape-2031539_1280.jpg)">
<h3>Explore the world</h3>
</div>
<div class="panel" style="background-image: url(https://cdn.pixabay.com/photo/2016/11/14/04/45/elephant-1822636_1280.jpg)">
<h3>Elephant</h3>
</div>
<div class="panel" style="background-image: url(https://cdn.pixabay.com/photo/2018/01/14/23/12/nature-3082832_1280.jpg)">
<h3>Lake</h3>
</div>
<div class="panel" style="background-image: url(https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885_1280.jpg)">
<h3>Jungle</h3>
</div>
<div class="panel" style="background-image: url(https://cdn.pixabay.com/photo/2015/09/09/16/05/forest-931706_1280.jpg)">
<h3>Forest</h3>
</div>
</div>
https://stackoverflow.com/questions/67039923
复制相似问题