Как работает галерея изображений? Одно основное изображение в центре с двумя рядами из 4 изображений, которое пользователь щелкает по изображению, которое отображается как основное изображение.
Я скрываю три галереи изображений в разделе и намерен отображать их на мобильных устройствах, приведенный ниже код JS работает только с первым набором галереи, две другие не отвечают.
//JS CODE
const current = document.querySelector("#current");
const imgs = document.querySelector(".imgs");
const img = document.querySelectorAll(".imgs img");
const opacity = 0.7;
// Set first img opacity
img[0].style.opacity = opacity;
imgs.addEventListener("click", imgClick);
function imgClick(e) {
// Reset the opacity
img.forEach(img => (img.style.opacity = 1));
// Change current image to src of clicked image
current.src = e.target.src;
// Add fade in class
current.classList.add("fade-in");
// Remove fade-in class after .5 seconds
setTimeout(() => current.classList.remove("fade-in"), 500);
// Change the opacity to opacity var
e.target.style.opacity = opacity;
} <section id = "portfolioProjects" class = "section section-a">
<div class = "container">
<div class = "row animate-box">
<div class = "col-md-8 col-md-offset-2 text-center fh5co-heading">
<h2 style = "color: #585555db">
Portfolio
</h2>
<p class = "psub-title-One">
some text
</p>
</div>
</div>
<ul class = "nav nav-tabs animate-box">
<li class = "active">
<a data-toggle = "tab" href = "#home">Simple WebSite</a>
</li>
<li><a data-toggle = "tab" href = "#menu1">Design</a></li>
<li><a data-toggle = "tab" href = "#menu2">Code Snippets</a></li>
</ul>
<div class = "tab-content">
<div id = "home" class = "tab-pane fade in active">
<br />
<div class = "animate-box">
<h2>Fully Functional Responsive Website</h2>
<p class = "about-text">
some text
</p>
</div>
<iframe
src = "https://codepen.io/dasilvabrunotexas/"
scrolling = "auto"
height = "900"
width = "100%"
class = "animate-box"
></iframe>
<!-- Hide Image Gallery on Big Screens-->
<!-- Hide Image Gallery on Big Screens-->
<div class = "container-gallery animate-box ">
<div class = "main-img">
<img src = "https://www.placecage.com/200/300" alt = "Image1" id = "current" />
</div>
<div class = "imgs">
<div class = "img-One animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div class = "img-two animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div
class = "img-three animate-box "
data-animate-effect = "fadeIn"
>
<img src = "https://www.placecage.com/200/300" />
</div>
<div class = "img-four animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div class = "img-five animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div class = "img-six animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div
class = "img-seven animate-box "
data-animate-effect = "fadeIn"
>
<img src = "https://www.placecage.com/200/300" />
</div>
<div
class = "img-eigth animate-box "
data-animate-effect = "fadeIn"
>
<img src = "https://www.placecage.com/200/300" />
</div>
</div>
</div>
<!-- END Hide Image Gallery on Big Screens-->
</div>
<!-- END First Portfolio Menu-->
<div id = "menu1" class = "tab-pane fade">
<br />
<h2>Graphic & Web Design Projects</h2>
<p class = "about-text">
some text
</p>
<!-- Hide Image Gallery on Big Screens-->
<!-- Hide Image Gallery on Big Screens-->
<div class = "container-gallery animate-box ">
<div class = "main-img">
<img src = "https://www.placecage.com/200/300" alt = "Image1" id = "current" />
</div>
<div class = "imgs">
<div class = "img-One animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div class = "img-two animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div
class = "img-three animate-box "
data-animate-effect = "fadeIn"
>
<img src = "https://www.placecage.com/200/300" />
</div>
<div class = "img-four animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div class = "img-five animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div class = "img-six animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div
class = "img-seven animate-box "
data-animate-effect = "fadeIn"
>
<img src = "https://www.placecage.com/200/300" />
</div>
<div
class = "img-eigth animate-box "
data-animate-effect = "fadeIn"
>
<img src = "https://www.placecage.com/200/300" />
</div>
</div>
</div>
<!-- END Hide Image Gallery on Big Screens-->
</div>
<!-- END First Menu-->
<div id = "menu2" class = "tab-pane fade">
<br />
<div class = "animate-box">
<h2>Tic-Tac-Toe Game</h2>
<p class = "about-text">
SOME TEXT
<a target = "_blank" href = "#"
><i style = "color:#ffcc5c" class = "fab fa-fly"></i>
</a>
to see more Projects on CodePen.
</p>
</div>
<iframe
src = "#"
height = "900"
width = "95%"
class = "animate-box"
></iframe>
<!-- Hide Image Gallery on Big Screens-->
<div class = "container-gallery animate-box ">
<div class = "main-img">
<img src = "https://www.placecage.com/200/300" alt = "Image1" id = "current" />
</div>
<div class = "imgs">
<div class = "img-One animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div class = "img-two animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div
class = "img-three animate-box "
data-animate-effect = "fadeIn"
>
<img src = "https://www.placecage.com/200/300" />
</div>
<div class = "img-four animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div class = "img-five animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div class = "img-six animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div
class = "img-seven animate-box "
data-animate-effect = "fadeIn"
>
<img src = "https://www.placecage.com/200/300" />
</div>
<div
class = "img-eigth animate-box "
data-animate-effect = "fadeIn"
>
<img src = "https://www.placecage.com/200/300" />
</div>
</div>
</div>
<!-- END Hide Image Gallery on Big Screens-->
</div>
</div>
</div>
<script src = "../dist/js/image-gallery.js"></script>
</section>
<br />


![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Я думаю, проблема в том, когда вы добавляете свой eventlistener в .imgs
.imgs выбирается с помощью querySelector, а не querySelectorAll, что означает, что он получает только первый.
Вероятно, вам просто нужно изменить свой селектор для imgs на querySelectorAll, а затем перебрать каждый из них, чтобы прикрепить прослушиватель событий.
//JS CODE
const current = document.querySelector("#current");
//const imgs = document.querySelector(".imgs");
const imgs = document.querySelectorAll(".imgs");
const img = document.querySelectorAll(".imgs img");
const opacity = 0.7;
// Set first img opacity
img[0].style.opacity = opacity;
//imgs.addEventListener("click", imgClick);
imgs.forEach( function(i) {
i.addEventListener("click", imgClick);
});
function imgClick(e) {
// Reset the opacity
img.forEach(img => (img.style.opacity = 1));
// Change current image to src of clicked image
current.src = e.target.src;
// Add fade in class
current.classList.add("fade-in");
// Remove fade-in class after .5 seconds
setTimeout(() => current.classList.remove("fade-in"), 500);
// Change the opacity to opacity var
e.target.style.opacity = opacity;
}<section id = "portfolioProjects" class = "section section-a">
<div class = "container">
<div class = "row animate-box">
<div class = "col-md-8 col-md-offset-2 text-center fh5co-heading">
<h2 style = "color: #585555db">
Portfolio
</h2>
<p class = "psub-title-One">
some text
</p>
</div>
</div>
<ul class = "nav nav-tabs animate-box">
<li class = "active">
<a data-toggle = "tab" href = "#home">Simple WebSite</a>
</li>
<li><a data-toggle = "tab" href = "#menu1">Design</a></li>
<li><a data-toggle = "tab" href = "#menu2">Code Snippets</a></li>
</ul>
<div class = "tab-content">
<div id = "home" class = "tab-pane fade in active">
<br />
<div class = "animate-box">
<h2>Fully Functional Responsive Website</h2>
<p class = "about-text">
some text
</p>
</div>
<iframe
src = "https://codepen.io/dasilvabrunotexas/"
scrolling = "auto"
height = "900"
width = "100%"
class = "animate-box"
></iframe>
<!-- Hide Image Gallery on Big Screens-->
<!-- Hide Image Gallery on Big Screens-->
<div class = "container-gallery animate-box ">
<div class = "main-img">
<img src = "https://www.placecage.com/200/300" alt = "Image1" id = "current" />
</div>
<div class = "imgs">
<div class = "img-One animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div class = "img-two animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div
class = "img-three animate-box "
data-animate-effect = "fadeIn"
>
<img src = "https://www.placecage.com/200/300" />
</div>
<div class = "img-four animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div class = "img-five animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div class = "img-six animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div
class = "img-seven animate-box "
data-animate-effect = "fadeIn"
>
<img src = "https://www.placecage.com/200/300" />
</div>
<div
class = "img-eigth animate-box "
data-animate-effect = "fadeIn"
>
<img src = "https://www.placecage.com/200/300" />
</div>
</div>
</div>
<!-- END Hide Image Gallery on Big Screens-->
</div>
<!-- END First Portfolio Menu-->
<div id = "menu1" class = "tab-pane fade">
<br />
<h2>Graphic & Web Design Projects</h2>
<p class = "about-text">
some text
</p>
<!-- Hide Image Gallery on Big Screens-->
<!-- Hide Image Gallery on Big Screens-->
<div class = "container-gallery animate-box ">
<div class = "main-img">
<img src = "https://www.placecage.com/200/300" alt = "Image1" id = "current" />
</div>
<div class = "imgs">
<div class = "img-One animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div class = "img-two animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div
class = "img-three animate-box "
data-animate-effect = "fadeIn"
>
<img src = "https://www.placecage.com/200/300" />
</div>
<div class = "img-four animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div class = "img-five animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div class = "img-six animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div
class = "img-seven animate-box "
data-animate-effect = "fadeIn"
>
<img src = "https://www.placecage.com/200/300" />
</div>
<div
class = "img-eigth animate-box "
data-animate-effect = "fadeIn"
>
<img src = "https://www.placecage.com/200/300" />
</div>
</div>
</div>
<!-- END Hide Image Gallery on Big Screens-->
</div>
<!-- END First Menu-->
<div id = "menu2" class = "tab-pane fade">
<br />
<div class = "animate-box">
<h2>Tic-Tac-Toe Game</h2>
<p class = "about-text">
SOME TEXT
<a target = "_blank" href = "#"
><i style = "color:#ffcc5c" class = "fab fa-fly"></i>
</a>
to see more Projects on CodePen.
</p>
</div>
<iframe
src = "#"
height = "900"
width = "95%"
class = "animate-box"
></iframe>
<!-- Hide Image Gallery on Big Screens-->
<div class = "container-gallery animate-box ">
<div class = "main-img">
<img src = "https://www.placecage.com/200/300" alt = "Image1" id = "current" />
</div>
<div class = "imgs">
<div class = "img-One animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div class = "img-two animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div
class = "img-three animate-box "
data-animate-effect = "fadeIn"
>
<img src = "https://www.placecage.com/200/300" />
</div>
<div class = "img-four animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div class = "img-five animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div class = "img-six animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div
class = "img-seven animate-box "
data-animate-effect = "fadeIn"
>
<img src = "https://www.placecage.com/200/300" />
</div>
<div
class = "img-eigth animate-box "
data-animate-effect = "fadeIn"
>
<img src = "https://www.placecage.com/200/300" />
</div>
</div>
</div>
<!-- END Hide Image Gallery on Big Screens-->
</div>
</div>
</div>
<script src = "../dist/js/image-gallery.js"></script>
</section>
<br />Знаете ли вы, могу ли я каким-то образом реализовать const current = document.querySelector("#current"); Итак, я могу проверить уникальный идентификатор в галерее изображений, и если есть идентификатор, выполнить функциональность еще раз?
Текущим будет тот, который вы нажали последним?
Никкурой, точно. Чтобы быть точным, вместо жесткого кода ID #current const current = document.querySelector("#current"); Я хотел бы запустить поиск поля идентификатора const current = document.querySelector("#" + SelectedID); а затем реализовать его в цикле, где он будет работать до тех пор, пока не будет найден новый идентификатор.
Есть пара проблем. Как правило, идентификаторы уникальны, поэтому у вас будет только один идентификатор на странице. Вы имеете в виду, что хотите выбрать все изображения с одинаковой позицией (например, img-six) или все изображения в одной контейнерной галерее? И когда вы говорите, что он будет работать до тех пор, пока будет найден новый идентификатор, вы имеете в виду, что он начнет постепенно отображать их по одному, как слайд-шоу?
Хорошо, что мне нужно сделать, так это заставить три галереи изображений работать независимо в одном разделе с использованием JS. Для этого мне нужно повторно использовать код JS в том же разделе. Как я могу это сделать? Я предполагаю, что мне нужно использовать querySelectorAll, а не жестко кодировать идентификатор, чтобы его можно было повторно использовать в том же разделе HTML и создать какой-то цикл, взаимодействующий с идентификаторами.
Используйте идентификаторы для разделов и делайте выбор на основе идентификатора > класса. Например: document.queryselectorAll("#imageGallery1 .imgGalleryItem"); Вы можете обернуть этот код в объект GalleryManager и создать экземпляр объекта менеджера галереи для каждой коллекции, который принимает идентификатор галереи, которой вы хотите управлять. Затем используйте указанный выше селектор для выбора и управления элементами только внутри этой галереи.
Атрибут id должен быть уникальным на странице. Когда вы выбираете элемент с помощью селектора идентификатора, он получает только первый элемент в дереве DOM.
Вместо этого замените это классом. Также у вас есть 3 галереи изображений в вашем фрагменте, и вам нужно будет добавить функциональность для изображений в каждой галерее. То, как вы написали, учитывает все изображения, не относящиеся к конкретной галерее.
//JS CODE
const imageContainers = document.querySelectorAll(".imgs");
const opacity = 0.7;
// Set the opacity for first image in each container
imageContainers.forEach((imageContainer) => {
imageContainer.querySelectorAll('.imgs img')[0].style.opacity = opacity;
});
// attach the click event for all the images inside the containers
imageContainers.forEach((imageContainer) => imageContainer.addEventListener("click", imgClick));
function imgClick(e) {
let currentContainer = e.currentTarget;
let currentContainerImages = currentContainer.querySelectorAll('img');
let currentImage = currentContainer.parentNode.querySelector('.current');
// update opacity for each image in container
currentContainerImages.forEach(img => (img.style.opacity = 1));
// Change current image to src of clicked image
currentImage.src = e.target.src;
// Add fade in class
currentImage.classList.add("fade-in");
// Remove fade-in class after .5 seconds
setTimeout(() => currentImage.classList.remove("fade-in"), 500);
// Change the opacity to opacity var
e.target.style.opacity = opacity;
}<section id = "portfolioProjects" class = "section section-a">
<div class = "container">
<div class = "row animate-box">
<div class = "col-md-8 col-md-offset-2 text-center fh5co-heading">
<h2 style = "color: #585555db">
Portfolio
</h2>
<p class = "psub-title-One">
some text
</p>
</div>
</div>
<ul class = "nav nav-tabs animate-box">
<li class = "active">
<a data-toggle = "tab" href = "#home">Simple WebSite</a>
</li>
<li><a data-toggle = "tab" href = "#menu1">Design</a></li>
<li><a data-toggle = "tab" href = "#menu2">Code Snippets</a></li>
</ul>
<div class = "tab-content">
<div id = "home" class = "tab-pane fade in active">
<br />
<div class = "animate-box">
<h2>Fully Functional Responsive Website</h2>
<p class = "about-text">
some text
</p>
</div>
<iframe src = "https://codepen.io/dasilvabrunotexas/" scrolling = "auto" height = "900" width = "100%" class = "animate-box"></iframe>
<!-- Hide Image Gallery on Big Screens-->
<!-- Hide Image Gallery on Big Screens-->
<div class = "container-gallery animate-box ">
<div class = "main-img">
<img src = "https://www.placecage.com/200/300" alt = "Image1" class = "current" />
</div>
<div class = "imgs">
<div class = "img-One animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div class = "img-two animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div class = "img-three animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div class = "img-four animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div class = "img-five animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div class = "img-six animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div class = "img-seven animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div class = "img-eigth animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
</div>
</div>
<!-- END Hide Image Gallery on Big Screens-->
</div>
<!-- END First Portfolio Menu-->
<div id = "menu1" class = "tab-pane fade">
<br />
<h2>Graphic & Web Design Projects</h2>
<p class = "about-text">
some text
</p>
<!-- Hide Image Gallery on Big Screens-->
<!-- Hide Image Gallery on Big Screens-->
<div class = "container-gallery animate-box ">
<div class = "main-img">
<img src = "https://www.placecage.com/200/300" alt = "Image1" class = "current" />
</div>
<div class = "imgs">
<div class = "img-One animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div class = "img-two animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div class = "img-three animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div class = "img-four animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div class = "img-five animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div class = "img-six animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div class = "img-seven animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div class = "img-eigth animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
</div>
</div>
<!-- END Hide Image Gallery on Big Screens-->
</div>
<!-- END First Menu-->
<div id = "menu2" class = "tab-pane fade">
<br />
<div class = "animate-box">
<h2>Tic-Tac-Toe Game</h2>
<p class = "about-text">
SOME TEXT
<a target = "_blank" href = "#"><i style = "color:#ffcc5c" class = "fab fa-fly"></i>
</a> to see more Projects on CodePen.
</p>
</div>
<iframe src = "#" height = "900" width = "95%" class = "animate-box"></iframe>
<!-- Hide Image Gallery on Big Screens-->
<div class = "container-gallery animate-box ">
<div class = "main-img">
<img src = "https://www.placecage.com/200/300" alt = "Image1" class = "current" />
</div>
<div class = "imgs">
<div class = "img-One animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div class = "img-two animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div class = "img-three animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div class = "img-four animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div class = "img-five animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div class = "img-six animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div class = "img-seven animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
<div class = "img-eigth animate-box " data-animate-effect = "fadeIn">
<img src = "https://www.placecage.com/200/300" />
</div>
</div>
</div>
<!-- END Hide Image Gallery on Big Screens-->
</div>
</div>
</div>
<script src = "../dist/js/image-gallery.js"></script>
</section>
<br />Спасибо за ваш ответ, Sunshanth, я сделал именно так, как вы советовали, я добавил функциональность в галереи, также я попытался создать второй файл JS с уникальными классами для тестирования, но он все еще не работает, хотя самая первая галерея работает отлично, вторая и третья нажимаю на картинку ничего не происходит.
Спасибо за ваш ответ, Nixkuroi, я попробовал это и вижу, что непрозрачность теперь отображается во второй и третьей галерее изображений, однако основное изображение не меняется при нажатии :(