如何防止类选择器附加到特定元素?

时间:2020-06-30 01:22:20

标签: javascript

我正在尝试解决此图像轮播的问题。我有典型的“下一个”和“上一个”按钮。单击该按钮时,JavaScript将“ current”类添加到进行处理的div中,并将其从当前的div中删除,从而使“ current”的不透明度为“ 1”,其余的为“ 0”。

下一个按钮可以正常工作。它会连续遍历所有div,然后从头开始。但是,上一个按钮将“当前”类添加到位于横幅顶部的徽标中。这使得徽标有点像横幅图像。我使用nth-child(2)作为开始,因为从技术上讲,第一个孩子是徽标图片。

解决此问题的最佳选择是什么?谢谢。

**HTML**

<div class="banner">
        <img class="logo" src="img/logo-hollow.png" alt="logo">
    
        <div class="banner-slide current"></div>
        <div class="banner-slide"></div>
        <div class="banner-slide"></div>
        <div class="banner-slide"></div>
        <div class="banner-slide"></div>
    </div>
**CSS**

.banner-slide {
    position:absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    opacity: 0;
    transition: opacity 0.4s ease-in-out;
  }

.banner-slide.current {
    opacity: 1;
}

.banner-slide:nth-child(2) {
    background: url('../img/slider-1.jpg') no-repeat center center/cover;
}

.banner-slide:nth-child(3) {
    background: url('../img/slider-2.jpg') no-repeat center center/cover;
}

.banner-slide:nth-child(4) {
    background: url('../img/slider-3.jpg') no-repeat center center/cover;
}

.banner-slide:nth-child(5) {
    background: url('../img/slider-4.jpg') no-repeat center center/cover;
}

.banner-slide:nth-child(6) {
    background: url('../img/slider-5.jpg') no-repeat center center/cover;
}
**JavaScript**

const slides = document.querySelectorAll('.banner-slide');
const next = document.querySelector('#next');
const prev = document.querySelector('#prev');

const nextSlide = () => {
  // Get Current Class
  const current = document.querySelector('.current');
  // Remove Current Class
  current.classList.remove('current');
  // Check for next slide
  if(current.nextElementSibling) {
    // Add current to next sibling
    current.nextElementSibling.classList.add('current');
  } else {
    // Add current to start
    slides[0].classList.add('current');
  }
  setTimeout(() => current.classList.remove('current'));
}

const prevSlide = () => {
  // Get Current Class
  const current = document.querySelector('.current');
  // Remove Current Class
  current.classList.remove('current');
  // Check for prev slide
  if(current.previousElementSibling) {
    // Add current to next sibling
    current.previousElementSibling.classList.add('current');
  } else {
    // Add current to last
    slides[slides.length - 1].classList.add('current');
  }
  setTimeout(() => current.classList.remove('current'));
};

// Button Events
next.addEventListener('click', e => {
  nextSlide();
});

prev.addEventListener('click', e => {
  prevSlide();
});

0 个答案:

没有答案