我正在尝试使我的网站响应手持设备的操作。我有四个图像,所有图像都带有class =“ grid-photos”。我试图使照片在单击时扩展,并在再次单击时关闭。
<div class="grid-container">
<img class="grid-photos">
<img class="grid-photos">
<img class="grid-photos">
<img class="grid-photos">
截至目前,我可以使用此Javascript使它仅与第一张图片一起使用
const gridPhotos = document.querySelector(".grid-photos");
document.querySelectorAll(".grid-photos").forEach((item) => {
item.addEventListener("click", (event) => {
gridPhotos.classList.toggle("expander");
});
});
我已经尝试使用[i]来查询querySelectorAll,但无济于事。
感谢您的任何帮助
问题在于您的变量gridPhotos
是所有网格照片的集合。因此,当您调用.classList
它时,会收到有关其未定义的错误消息。
您需要做的是从事件中获取正确的元素。event.target
将返回被单击的元素,因此您可以使用该元素将类添加到正确的图像。
document.querySelectorAll(".grid-photos").forEach((item) => {
item.addEventListener("click", (event) => {
event.target.classList.toggle("expander");
});
});
.expander {
border: 4px solid green; /* Added to highlight which one was clicked */
}
<div class="grid-container">
<img class="grid-photos" src="https://lh6.googleusercontent.com/-l7M0ldZDNZs/AAAAAAAAAAI/AAAAAAAAAAA/ACHi3rf7tyiXmVY3yNjeGjVZCZdKL2qObw/photo.jpg?sz=32">
<img class="grid-photos" src="https://lh6.googleusercontent.com/-l7M0ldZDNZs/AAAAAAAAAAI/AAAAAAAAAAA/ACHi3rf7tyiXmVY3yNjeGjVZCZdKL2qObw/photo.jpg?sz=32">
<img class="grid-photos" src="https://lh6.googleusercontent.com/-l7M0ldZDNZs/AAAAAAAAAAI/AAAAAAAAAAA/ACHi3rf7tyiXmVY3yNjeGjVZCZdKL2qObw/photo.jpg?sz=32">
<img class="grid-photos" src="https://lh6.googleusercontent.com/-l7M0ldZDNZs/AAAAAAAAAAI/AAAAAAAAAAA/ACHi3rf7tyiXmVY3yNjeGjVZCZdKL2qObw/photo.jpg?sz=32">
</div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句