Как точки указывают и управляют слайдером с изображениями - PullRequest
0 голосов
/ 02 июля 2019

Я пытаюсь построить активные точки для своего слайдера, и я нашел некоторую ссылку на w3schools, но я не понимаю логику функции, которая управляет точками.Кто-нибудь может объяснить мне, как они работают в коде ниже?

Чтобы упомянуть: я знаю, как работает слайдер, но я не понимаю, как работают точки!

var slideIndex = 1;
showSlides(slideIndex);

// Next/previous controls
function plusSlides(n) {
  showSlides(slideIndex += n);
}

// Thumbnail image controls
function currentSlide(n) {
  showSlides(slideIndex = n);
}

function showSlides(n) {
  var i;
  var slides = document.getElementsByClassName("mySlides");
  var dots = document.getElementsByClassName("dot");
  if (n > slides.length) {slideIndex = 1} 
  if (n < 1) {slideIndex = slides.length}
  for (i = 0; i < slides.length; i++) {
      slides[i].style.display = "none"; 
  }
  for (i = 0; i < dots.length; i++) {
      dots[i].className = dots[i].className.replace(" active", "");
  }
  slides[slideIndex-1].style.display = "block"; 
  dots[slideIndex-1].className += " active";
}
* {box-sizing:border-box}

/* Slideshow container */
.slideshow-container {
  max-width: 1000px;
  position: relative;
  margin: auto;
}

/* Hide the images by default */
.mySlides {
  display: none;
}

/* Next & previous buttons */
.prev, .next {
  cursor: pointer;
  position: absolute;
  top: 50%;
  width: auto;
  margin-top: -22px;
  padding: 16px;
  color: white;
  font-weight: bold;
  font-size: 18px;
  transition: 0.6s ease;
  border-radius: 0 3px 3px 0;
  user-select: none;
}

/* Position the "next button" to the right */
.next {
  right: 0;
  border-radius: 3px 0 0 3px;
}

/* On hover, add a black background color with a little bit see-through */
.prev:hover, .next:hover {
  background-color: rgba(0,0,0,0.8);
}

/* Caption text */
.text {
  color: #f2f2f2;
  font-size: 15px;
  padding: 8px 12px;
  position: absolute;
  bottom: 8px;
  width: 100%;
  text-align: center;
}

/* Number text (1/3 etc) */
.numbertext {
  color: #f2f2f2;
  font-size: 12px;
  padding: 8px 12px;
  position: absolute;
  top: 0;
}

/* The dots/bullets/indicators */
.dot {
  cursor: pointer;
  height: 15px;
  width: 15px;
  margin: 0 2px;
  background-color: #bbb;
  border-radius: 50%;
  display: inline-block;
  transition: background-color 0.6s ease;
}

.active, .dot:hover {
  background-color: #717171;
}

/* Fading animation */
.fade {
  -webkit-animation-name: fade;
  -webkit-animation-duration: 1.5s;
  animation-name: fade;
  animation-duration: 1.5s;
}

@-webkit-keyframes fade {
  from {opacity: .4} 
  to {opacity: 1}
}

@keyframes fade {
  from {opacity: .4} 
  to {opacity: 1}
}
<!-- Slideshow container -->
<div class="slideshow-container">

  <!-- Full-width images with number and caption text -->
  <div class="mySlides fade">
    <div class="numbertext">1 / 3</div>
    <img src="img1.jpg" style="width:100%">
    <div class="text">Caption Text</div>
  </div>

  <div class="mySlides fade">
    <div class="numbertext">2 / 3</div>
    <img src="img2.jpg" style="width:100%">
    <div class="text">Caption Two</div>
  </div>

  <div class="mySlides fade">
    <div class="numbertext">3 / 3</div>
    <img src="img3.jpg" style="width:100%">
    <div class="text">Caption Three</div>
  </div>

  <!-- Next and previous buttons -->
  <a class="prev" onclick="plusSlides(-1)">&#10094;</a>
  <a class="next" onclick="plusSlides(1)">&#10095;</a>
</div>
<br>

<!-- The dots/circles -->
<div style="text-align:center">
  <span class="dot" onclick="currentSlide(1)"></span> 
  <span class="dot" onclick="currentSlide(2)"></span> 
  <span class="dot" onclick="currentSlide(3)"></span> 
</div>

Ответы [ 2 ]

0 голосов
/ 02 июля 2019

Я пытаюсь получить то же самое, но единственное, что не работает, это активный класс ... даже если я пытаюсь добавить его через html, все равно не работает.

var sliderIndex = 0;

let next2 = document.querySelector(".next2");
let prev2 = document.querySelector(".prev2");

function showNews(n) {
  debugger;
  const slider = document.getElementsByClassName('news');
  const dots = document.getElementsByClassName('dot');
  for (i = 0; i < slider.length; i++) {
    slider[i].style.display = 'none';
  }
  if (n < 0) {
    sliderIndex = slider.length - 1;
  }
  if (n > slider.length - 1) {
    sliderIndex = 0
  }
  for (i = 0; i < dots.length; i++) {
    dots[i].className = dots[i].className.replace(" active", " ");
  }
  slider[sliderIndex].style.display = 'block';
  dots[sliderIndex].className += " active"
}

function currentSlide(n) {
  showNews(sliderIndex = n)
}

function incrementSlides2(n) {
  showNews((sliderIndex += n))
}

next2.addEventListener("click", function () {
  incrementSlides2(1);
});
prev2.addEventListener("click", function () {
  incrementSlides2(-1);
});

showNews(sliderIndex)
#section-three .slideshow-container2 {
  position: relative;
}

#section-three .slideshow-container2 .prev2,
#section-three .slideshow-container2 .next2 {
  top: 50%;
  background: blue;
  font-size: 18px;
  border-radius: 0 3px 3px 0;
  width: auto;
  position: absolute;
  padding: 16px;
}

#section-three .slideshow-container2 .next2 {
  right: 0;
  border-radius: 3px 0 0 3px;
}

#section-three .slideshow-container2 .prev2:hover,
#section-three .slideshow-container2 .next2:hover {
  background-color: rgba(0, 0, 0, 0.8);
}

#section-three .slideshow-container2 .buttons {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: center;
      -ms-flex-pack: center;
          justify-content: center;
  margin-bottom: 4rem;
}

#section-three .slideshow-container2 .buttons .company-btn,
#section-three .slideshow-container2 .buttons .industry-btn {
  margin: 1.5rem;
  display: inline-block;
  padding: 0.8rem 1rem;
  background: black;
  border-radius: 0;
  -webkit-transition: 0s;
  transition: 0s;
}

#section-three .slideshow-container2 .buttons .company-btn:hover {
  background: white;
  color: black;
}

#section-three .slideshow-container2 .buttons .industry-btn {
  background: white;
  color: black;
}

#section-three .slideshow-container2 .buttons .industry-btn:hover {
  background: black;
  color: white;
}

#section-three .slideshow-container2 .news-content,
#section-three .slideshow-container2 .news2-content {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
      -ms-flex-direction: column;
          flex-direction: column;
  -webkit-box-pack: center;
      -ms-flex-pack: center;
          justify-content: center;
  -webkit-box-align: center;
      -ms-flex-align: center;
          align-items: center;
  height: 600px;
  background: white;
  text-align: center;
}

#section-three .slideshow-container2 .news-content p,
#section-three .slideshow-container2 .news2-content p {
  font-size: 1.2rem;
  padding: 2rem 8rem;
}

#section-three .slideshow-container2 .news-content h1,
#section-three .slideshow-container2 .news2-content h1 {
  font-family: Arial, Helvetica, sans-serif;
  font-size: 1.5rem;
}

#section-three .slideshow-container2 .news2-content {
  background: white;
  display: -ms-grid;
  display: grid;
  -ms-grid-rows: (1fr)[3];
      grid-template-rows: repeat(3, 1fr);
  -ms-grid-columns: (1fr)[3];
      grid-template-columns: repeat(3, 1fr);
  padding: 1.5rem 6rem;
}

#section-three .slideshow-container2 .buttons {
  -ms-grid-column: 1;
  -ms-grid-column-span: 3;
  grid-column: 1/4;
  -ms-grid-row: 1;
  grid-row: 1;
  -webkit-box-pack: center;
      -ms-flex-pack: center;
          justify-content: center;
  margin-bottom: 1rem;
}

#section-three .slideshow-container2 .media-room {
  -ms-grid-row: 2;
  grid-row: 2;
  -ms-grid-column: 1;
  -ms-grid-column-span: 1;
  grid-column: 1/2;
}

#section-three .slideshow-container2 .img {
  -ms-grid-column: 1;
  -ms-grid-column-span: 1;
  grid-column: 1/2;
  -ms-grid-row: 3;
  grid-row: 3;
  margin-right: 1rem;
}

#section-three .slideshow-container2 .texter {
  -ms-grid-column: 2;
  -ms-grid-column-span: 2;
  grid-column: 2/4;
  -ms-grid-row: 3;
  grid-row: 3;
  padding: 0 !important;
}

#section-three .slideshow-container2 .wiew-more {
  color: green;
  -ms-grid-row: 4;
  grid-row: 4;
  -ms-grid-column: 1;
  -ms-grid-column-span: 3;
  grid-column: 1/4;
}

#section-three .slideshow-container2 #dots {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: center;
      -ms-flex-pack: center;
          justify-content: center;
}

#section-three .slideshow-container2 #dots .dot {
  cursor: pointer;
  height: 15px;
  width: 15px;
  margin: 0 2px;
  background-color: #bbb;
  border-radius: 50%;
  display: inline-block;
  -webkit-transition: background-color 0.6s ease;
  transition: background-color 0.6s ease;
}

#section-three .slideshow-container2 #dots .dot:hover,
#section-three .slideshow-container2 #dots .dot .active {
  background: black;
}
<section id="section-three">
    <div class="container slideshow-container2">
      <div class="news">
        <div class="news-content">
          <div class="buttons">
            <a class="btn company-btn" href="#">COMPANY NEWS</a>
            <a class="btn industry-btn" href="#">INDUSTRY NEWS</a>
          </div>
          <h1>OUR PEOPLE ARE OUT STONGEST ASSET </h1>
          <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Iusto voluptate fugiat, molestias adipisci
            voluptas
            nisi blanditiis a aliquid accusantium omnis, soluta animi praesentium ipsam fugit? Non ea nisi optio
            dolores.voluptate fugiat, molestias adipisci voluptas
            nisi blanditiis a aliquid accusantium omnis, soluta animi praesentium ipsam fugit? Non ea nisi optio
            dolores.
          </p>
          <a class="my-2 wiew-more" href="#">WIEW MORE</a>
        </div>
      </div>
      <div class="news news2">
        <div class="news2-content">
          <div class="buttons">
            <a class="btn company-btn" href="#">COMPANY NEWS</a>
            <a class="btn industry-btn" href="#">INDUSTRY NEWS</a>
          </div>
          <h1 class="media-room">MEDIA ROOM </h1>
          <div class="img">
            <img src="/Core/img/media.jpg" style="width:500px" alt="">
          </div>
          <p class="texter">London, June 2019 – If you want to enjoy wireless technology while gaming an unnoticeable
            latency is key.
            Sennheiser introduces the GSP 670, Sennheiser's first wireless gaming headset. The GSP 670 gives gamers
            significantly more freedom of movement than wired models. The audio specialist has integrated a proprietary
            low-latency connection that guarantees a reliable and stable transmission with near-zero delay. In addition,
            the GSP 670 offers Sennheiser’s renowned wearing comfort and premium audio performance.

          </p>
          <a class="my-2 wiew-more" href="#">WIEW MORE2</a>
        </div>
      </div>
      <div id="dots">
        <span class="dot active" onclick="currentSlide(1)"></span>
        <span class="dot" onclick="currentSlide(2)"></span>
      </div>
      <a href="javascript:void(0);" class="prev2">Prev</a>
      <a href="javascript:void(0);" class="next2">Next</a>
    </div>
  </section>
0 голосов
/ 02 июля 2019

При нажатии одной из точек вызывается метод currentSlide с соответствующим параметром. Затем вызывается метод showSlides (с тем же параметром), который выполняет следующее:

  • сохраняет коллекцию элементов с именем класса mySlides и точкой в две переменные:
var slides = document.getElementsByClassName("mySlides");
var dots = document.getElementsByClassName("dot");

Для получения дополнительной информации:

getElementsByClassName () Документация

  • если переданный параметр больше или меньше количества слайдов (если, например, существует больше точек, чем слайдов), то для индекса, который будет отображаться, устанавливается значение, чтобы по-прежнему отображать слайд
if (n > slides.length) {slideIndex = 1} 
if (n < 1) {slideIndex =slides.length}
  • для каждого слайда установлено значение свойства none
for (i = 0; i < slides.length; i++) {
      slides[i].style.display = "none"; 
  }

Для получения дополнительной информации:

Стиль отображения Документация по недвижимости

Отображение CSS Документация по недвижимости

  • класс active удаляется из всех точек
for (i = 0; i < dots.length; i++) {
      dots[i].className = dots[i].className.replace(" active", "");
  }
  • значение отображения свойства установлено в блок для соответствующего слайда

слайды [slideIndex-1] .style.display = "block";

  • класс active добавлен к нажатой точке

точек [slideIndex-1] .className + = "active";

Надеюсь, этого достаточно:)

...