Как применить класс к разным блокам при наведении?

Рейтинг: 0Ответов: 1Опубликовано: 04.07.2023

При наведении на карточку сменяются картинки, проблема в том что при наведении на первую карточку товара, вторая начинает тоже пропадать. Подскажите как применить наведении для каждой карточке отдельно? Спасибо

const galleryItems = document.querySelectorAll('.product-card__item');

if (galleryItems) {
    galleryItems.forEach(item => {
        item.addEventListener("mouseenter", function (e) {
            galleryItems.forEach(el => { el.classList.remove('_active'); });
            item.classList.add('_active')
        });
        item.addEventListener("mouseleave", function (e) {
            galleryItems.forEach(el => { el.classList.remove('_active'); });
            galleryItems[0].classList.add('_active')
        });
    });
}
.product__body{
  display: flex;
}

.products__column{
  flex: 0 1 auto;
  margin: 0px 20px 0px 0px;
}

.product-card__images {
  display: flex;
  position: relative;
  height: 363px;
  width: 300px;
}

a {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  width: 100%;
  display: block;
  left: 0;
}

img {
  transition: opacity 0.2s ease-in-out;
  position: absolute;
  margin: auto;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  border: 0;
  vertical-align: middle;
  max-width: 100%;
  max-height: 100%;
  pointer-events: none;
  opacity: 0;
}

.product-card__item._active img{
  opacity: 1;
}

.product-card__items{
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        display: flex;
        flex-direction: row;
        z-index: 2;
    }

.product-card__item{
        flex-grow: 1;
        -webkit-box-flex: 1;
        -ms-flex-positive: 1;
        background-color: #fff;
        background: 0 0;
        margin: 0px 2px;
    }
<div class="product__body">
  <div class="products__column product-card">
    <div class="product-card__images">
      <a href="#">
        <span class="product-card__items">
          <span class="product-card__item _active">
            <img src="https://kisa.club/uploads/posts/2023-03/1679858194_kisa-club-p-stilnie-komplekti-odezhdi-instagram-4.jpg" alt>
          </span>
          <span class="product-card__item">
            <span class="product-card__item-nav"></span>
            <img src="https://kisa.club/uploads/posts/2023-04/1680336969_kisa-club-p-stil-odezhdi-devochki-krasivo-1.jpg" alt>
          </span>
        </span>
      </a>
    </div>
  </div>

  <div class="products__column product-card">
    <div class="product-card__images">
      <a href="#">
        <span class="product-card__items">
          <span class="product-card__item _active">
            <img src="https://kisa.club/uploads/posts/2023-03/1679858194_kisa-club-p-stilnie-komplekti-odezhdi-instagram-4.jpg" alt>
          </span>
        </span>
      </a>
    </div>
  </div>
</div>

Ответы

▲ 1Принят

Можно совсем без js. Только с использованием hover.

.product__body{
  display: flex;
}


.products__column{
  flex: 0 1 auto;
  margin: 0px 20px 0px 0px;
}

.product-card__images {
  display: flex;
  position: relative;
  height: 363px;
  width: 300px;
}

a {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  width: 100%;
  display: block;
  left: 0;
}

img {
  transition: opacity 0.2s ease-in-out;
  position: absolute;
  margin: auto;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  border: 0;
  vertical-align: middle;
  max-width: 100%;
  max-height: 100%;
  pointer-events: none;
  opacity: 1;
}

.product-card__items{
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        display: flex;
        flex-direction: row;
        z-index: 2;
    }
    
  
.product-card__items:hover .product-card__item:first-child img{
      opacity: 0;
}
    
.product-card__items .product-card__item:nth-child(2) img{
      opacity: 0;
}
    
.product-card__items:hover .product-card__item:nth-child(2) img {
     opacity: 1;
}


.product-card__item{
        flex-grow: 1;
        -webkit-box-flex: 1;
        -ms-flex-positive: 1;
        background-color: #fff;
        background: 0 0;
        margin: 0px 2px;
    }
<div class="product__body">
  <div class="products__column product-card">
    <div class="product-card__images">
      <a href="#">
        <span class="product-card__items">
          <span class="product-card__item">
            <img src="https://kisa.club/uploads/posts/2023-03/1679858194_kisa-club-p-stilnie-komplekti-odezhdi-instagram-4.jpg" alt>
          </span>
          <span class="product-card__item">
            <span class="product-card__item-nav"></span>
            <img src="https://kisa.club/uploads/posts/2023-04/1680336969_kisa-club-p-stil-odezhdi-devochki-krasivo-1.jpg" alt>
          </span>
        </span>
      </a>
    </div>
  </div>

  <div class="products__column product-card">
    <div class="product-card__images">
      <a href="#">
        <span class="product-card__items">
          <span class="product-card__item">
            <img src="https://kisa.club/uploads/posts/2023-03/1679858194_kisa-club-p-stilnie-komplekti-odezhdi-instagram-4.jpg" alt>
          </span>
        </span>
      </a>
    </div>
  </div>
</div>

Если разбирать ваш код с js. Вы изначально берёте всю коллекцию элементов product-card__item, что не совсем верно, поскольку у них разные родители. И соответственно при наведении везде удаляете класс _active во всех родительских контейнерах, а не только в том, на который наводите мышь. Как вариант за изначальную коллекцию элементов можно брать родительские блоки product-card__items. И при наведении на него уже работать с конкретными потомками product-card__item.

const galleryItems = document.querySelectorAll('.product-card__items');

if (galleryItems) {
galleryItems.forEach(item => {
    item.addEventListener("mouseenter", function (e) {
        item.querySelector('.product-card__item:first-child').classList.remove('_active');
        item.querySelector('.product-card__item:nth-child(2)').classList.add('_active');
    });
    item.addEventListener("mouseleave", function (e) {
        item.querySelector('.product-card__item:first-child').classList.add('_active');
        item.querySelector('.product-card__item:nth-child(2)').classList.remove('_active');
    });
});
}
   body {
  background: transparent; /* Make it white if you need */
  color: #fcbe24;
  padding: 0 24px;
  margin: 0;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}

.product__body{
  display: flex;
}

.products__column{
  flex: 0 1 auto;
  margin: 0px 20px 0px 0px;
}

.product-card__images {
  display: flex;
  position: relative;
  height: 363px;
  width: 300px;
}

a {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  width: 100%;
  display: block;
  left: 0;
}

img {
  transition: opacity 0.2s ease-in-out;
  position: absolute;
  margin: auto;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  border: 0;
  vertical-align: middle;
  max-width: 100%;
  max-height: 100%;
  pointer-events: none;
  opacity: 0;
}

.product-card__item._active img{
  opacity: 1;
}

.product-card__items{
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    display: flex;
    flex-direction: row;
    z-index: 2;
}

.product-card__item{
    flex-grow: 1;
    -webkit-box-flex: 1;
    -ms-flex-positive: 1;
    background-color: #fff;
    background: 0 0;
    margin: 0px 2px;
}
<div class="product__body">
  <div class="products__column product-card">
    <div class="product-card__images">
      <a href="#">
        <span class="product-card__items">
          <span class="product-card__item _active">
            <img src="https://kisa.club/uploads/posts/2023-03/1679858194_kisa-club-p-stilnie-komplekti-odezhdi-instagram-4.jpg" alt>
          </span>
          <span class="product-card__item">
            <span class="product-card__item-nav"></span>
            <img src="https://kisa.club/uploads/posts/2023-04/1680336969_kisa-club-p-stil-odezhdi-devochki-krasivo-1.jpg" alt>
          </span>
        </span>
      </a>
    </div>
  </div>


  <div class="products__column product-card">
<div class="product-card__images">
  <a href="#">
    <span class="product-card__items">
      <span class="product-card__item _active">
        <img src="https://kisa.club/uploads/posts/2023-03/1679858194_kisa-club-p-stilnie-komplekti-odezhdi-instagram-4.jpg" alt>
      </span>
       <span class="product-card__item">
        <span class="product-card__item-nav"></span>
        <img src="https://kisa.club/uploads/posts/2023-04/1680336969_kisa-club-p-stil-odezhdi-devochki-krasivo-1.jpg" alt>
      </span>
    </span>
  </a>
</div>
  </div>
</div>