gpt4 book ai didi

javascript - JS : addClass on click and removeClass on window click (or outside of div)

转载 作者:行者123 更新时间:2023-12-04 07:22:38 24 4
gpt4 key购买 nike

我正在尝试添加 classList到元素“onclick”,然后删除 classList任何点击后。

const images = document.querySelectorAll(".section-projects-img");

images.forEach(img => {
img.addEventListener("click", () => {
img.classList.toggle("changed");
});
});
这会在我点击图片时添加/删除,但我希望无论我点击哪里都将其删除,以便多个 img 不能有相同的 classList .我试过添加 classList到元素然后使用 classList.contains() 删除.这看起来 super 简单,而且很尴尬,我无法弄清楚。先谢谢了!

最佳答案

因为事件从事件目标一直冒泡到顶级元素,我们可以这样做:

// just one event listener
document.body.addEventListener('click', clickEventDispatch, false);

function clickEventDispatch (e) {

var _evt = (e.target || this);

console.log(_evt.nodeName, _evt.className);

/*
in practice you might want to change the criteria,
and indeed possibly use if/else if instead of switch,
but this will do for the purposes of demonstration:
*/
switch (_evt.nodeName) {
// it's an image
case "IMG":
/*
EDIT:
Didn't realise you wanted to toggle if active image clicked
This oughta do it
*/
if (_evt.classList.contains('changed')) {
_evt.classList.remove('changed')
}
else {
resetChangedImages();
_evt.classList.add('changed')
};
break;

// it's not an image
default:
resetChangedImages();
}

}

function resetChangedImages () {
/*
[].slice.call here just converts the NodeList we get
from querySelectorAll into an Array we can iterate over
with forEach, rather than having to use for loop
*/
[].slice.call(document.querySelectorAll('img')).forEach(function (img) {
img.classList.remove('changed');
});
}
.container {
padding: 32px 16px 200px;
background: #d1d1d1;
}
.section-projects-img {
border: 2px solid #fff;
}
.changed {
border-color: red;
}
<div class="container">
<img class="section-projects-img" src="https://i.imgur.com/2BLYrIxs.jpg" />
<img class="section-projects-img" src="https://i.imgur.com/PIdF6ANs.jpg" />
<img class="section-projects-img" src="https://i.imgur.com/uVm9rTfs.jpg" />
<img class="section-projects-img" src="https://i.imgur.com/6x0UzSVs.jpg" />
<img class="section-projects-img" src="https://i.imgur.com/mvqzSFMs.jpg" />
</div>

这意味着我们不会为每个图像添加一个事件监听器,只是在主体上添加一个事件监听器,然后如果您需要其他元素(如按钮等)的事件监听器,您可以将它们包含在您的事件调度程序函数中。

关于javascript - JS : addClass on click and removeClass on window click (or outside of div),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68402481/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com