如何删除一个类时,另一个元素被点击?



我想创建一个简单的图库。当图像被点击时,它会被调整大小。但是,当我点击另一个图像时,第一个图像仍然是活动的。如何删除类时,我点击另一个图像?

const imgList = document.querySelectorAll("img");
console.log(imgList);
for (let i = 0; i < imgList.length; i++) {
imgList[i].addEventListener("click", function () {
imgList[i].classList.toggle("bigger");
});
}

无需使其复杂化,您只需从所有图像中重置删除bigger并将其设置为单击的图像

const imgList = document.querySelectorAll("img");
for (let i = 0; i < imgList.length; i++) {
imgList[i].addEventListener("click", function () {
imgList.forEach(el=> el.classList.remove("bigger"))
imgList[i].classList.add("bigger");
});
}

有几种方法可以做到这一点。一种方法是简单地找到先前选择的项,并在单击新类时删除该类:

const currentlySelectedElem = document.querySelector("img.bigger");
if (currentlySelectedElem) {
currentlySelectedElem.classList.remove("bigger");
}

在上下文中,它可能看起来像这样:

document.querySelectorAll("img").forEach(imgElem => {
imgElem.addEventListener("click", function () {
// Deselect the last selected image by selecting it and removing the class if needed
const currentlySelectedElem = document.querySelector("img.bigger");
if (currentlySelectedElem) {
currentlySelectedElem.classList.remove("bigger");
}

// Indicate the current selection
imgElem.classList.add("bigger");
});
});
img {
width: 64px;
height: 64px;
}
img.bigger {
width: 128px;
height: 128px;
}
<img src="https://placeimg.com/200/200/any" />
<img src="https://placeimg.com/200/200/any" />
<img src="https://placeimg.com/200/200/any" />
<img src="https://placeimg.com/200/200/any" />
<img src="https://placeimg.com/200/200/any" />

相关内容

最新更新