js carousel chart sample code

The following is a simple JavaScript carousel sample code:

HTML:

<div class="slideshow-container">
  <div class="slide fade">
    <img src="img1.jpg">
  </div>
  <div class="slide fade">
    <img src="img2.jpg">
  </div>
  <div class="slide fade">
    <img src="img3.jpg">
  </div>
</div>

<button class="prev" onclick="plusSlides(-1)">❮</button>
<button class="next" onclick="plusSlides(1)">❯</button>

CSS:

.slideshow-container {
  position: relative;
  height: 400px;
}
.slideshow-container img {
  width: 100%;
  height: 400px;
}
.slide {
  position: absolute;
  width: 100%;
  height: 400px;
  display: none;
}
.prev, .next {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  z-index: 1;
  padding: 10px;
  font-size: 30px;
  font-weight: bold;
  color: #fff;
  background-color: rgba(0,0,0,0.5);
  border: none;
  cursor: pointer;
}
.prev {
  left: 0;
}
.next {
  right: 0;
}

JavaScript:

var slideIndex = 1;
showSlides(slideIndex);

function plusSlides(n) {
  showSlides(slideIndex += n);
}

function showSlides(n) {
  var i;
  var slides = document.getElementsByClassName("slide");
  if (n > slides.length) {slideIndex = 1}
  if (n < 1) {slideIndex = slides.length}
  for (i = 0; i < slides.length; i++) {
      slides[i].style.display = "none";
  }
  slides[slideIndex-1].style.display = "block";
}

This carousel contains three images, namely img1.jpg, img2.jpg, and img3.jpg. CSS defines the carousel container .slideshow-container and image style, as well as the button style of the carousel. The logic of the carousel chart is defined in JavaScript, including the two functions plusSlides() and showSlides(), as well as the showSlides(slideIndex) function that initializes the carousel chart. . Finally, the container and button of the carousel are defined in HTML.

Guess you like

Origin blog.csdn.net/song19990524/article/details/134746504