当我单击这些图像中的任何一个时,会弹出带有img的弹出窗口,我想使弹出窗口动态化,这意味着弹出窗口的img应该基于被单击的元素。
这是html结构:
<div class="gallery">
<img src="img/hg-1.jpg" alt="Interior view" class="gallery__img">
<img src="img/hg-2.jpg" alt="Interior view" class="gallery__img">
<img src="img/hg-3.jpg" alt="Interior view" class="gallery__img">
<img src="img/hg-4.jpg" alt="Interior view" class="gallery__img">
<img src="img/hg-5.jpg" alt="Interior view" class="gallery__img">
<img src="img/hg-6.jpg" alt="Interior view" class="gallery__img">
<img src="img/hg-7.jpg" alt="Interior view" class="gallery__img">
<img src="img/hg-8.jpg" alt="Interior view" class="gallery__img">
<img src="img/hg-9.jpg" alt="Interior view" class="gallery__img">
<img src="img/hg-10.jpg" alt="Interior view" class="gallery__img">
<img src="img/hg-11.jpg" alt="Interior view" class="gallery__img">
<img src="img/hg-12.jpg" alt="Interior view" class="gallery__img">
</div>
Js代码:
// Overlay template
const overlay = el => `
<div class="overlay">
<button class="overlay__close-icon" id="closeOverlay">×</button>
<img src="img/prev.png" alt="Previous button" class="overlay__btn">
<img src="img/hg-1.jpg" alt="Interior view" class="overlay__img">
<img src="img/next.png" alt="Next button" class="overlay__btn">
</div>`;
// Inject template to html structure
document.querySelector('#main').insertAdjacentHTML('beforeend', overlay);
const addClickEvent = () => {
document.querySelector('.overlay').classList.add('showOverlay')
document.querySelector('body').style.overflow = 'hidden'
};
let query = document.querySelector('.gallery');
let images = 'gallery__img';
if (!query) {
query = document.querySelector('.section-gallery');
images = 'section-' + images;
}
// Nodelist elements
const imageElems = document.querySelectorAll("." + images);
// Convert nodelist into array
let imgArr = [...imageElems];
// Open overlay
query.addEventListener('click', () => {
addClickEvent(imageElems)
// I want to make this piece of code dynamic,
// right now it's just returning the element of index 2.
document.querySelector('.overlay__img').src = imgArr[2].src;
});
// Close overlay
document.querySelector('#closeOverlay').addEventListener('click', () => {
document.querySelector('.overlay').classList.remove('showOverlay');
document.querySelector('body').style.overflow = 'auto'
});
我正在尝试根据数组中元素的索引更改弹出窗口的src,但是我遇到了问题。我知道如何使用Jquery进行此操作,但我只想在此项目中使用纯JS。预先感谢。
答案 0 :(得分:1)
通过event
参数在其容器中找到被单击元素的索引,然后可以在该索引处引用imgArr
:
query.addEventListener('click', (event) => {
const { target } = event;
// If the click was in the container but not on any of the images, return:
if (!target.matches('.gallery__img')) return;
addClickEvent(imageElems); // ???
const index = Array.prototype.indexOf.call(query.children, target);
document.querySelector('.overlay__img').src = imgArr[index].src;
});
(不确定您在addClickEvent(imageElems);
行中所做的工作-addClickEvent
在代码中不接受任何参数,可能更改为addClickEvent();
)