构建循环幻灯片的最简单的纯Javascript代码

The Simplest pure Javascript code to build a looping slideshow

本文关键字:Javascript 代码 最简单 幻灯片 构建 循环      更新时间:2023-09-26

我只是想学习javascript代码最简单的方法来构建幻灯片>它是如何理解一系列的div s or img并一个接一个地重复它们的??我知道这对你来说很简单,但我才刚刚开始!: D

从概念上讲,创建自动循环图像滑块的一种方法是让JavaScript代码反复运行(使用setInterval()setTimeout())来隐藏和显示页面上的图像,每次一个。

你只需要把你的图像元素放在一个数组中,你可以随意更新。

下面是一个没有任何动画效果的基本示例:

(function() {
  var selectedIndex = -1;
  var imgs = document.querySelectorAll(".slideshow img"),
    left = document.querySelector(".slideshow .left"),
    right = document.querySelector(".slideshow .right"),
    current = document.querySelector(".slideshow .current");
  var numSeconds = 2;
  var timeout;
  setIndex(0);
  left.addEventListener("click", function() {
    setIndex(selectedIndex - 1);
  });
  right.addEventListener("click", function() {
    setIndex(selectedIndex + 1);
  });
  function setIndex(i) {
    if (timeout) {
      clearTimeout(timeout);
    }
    if (selectedIndex >= 0) {
      imgs[selectedIndex].style.display = "none";
    }
    if (i >= imgs.length) {
      selectedIndex = 0;
    } else if (i < 0) {
      selectedIndex = 0;
    } else {
      selectedIndex = i;
    }
    imgs[selectedIndex].style.display = "inline-block";
    current.innerHTML = (selectedIndex + 1) + "/" + imgs.length;
    timeout = setTimeout(function() {
      setIndex(selectedIndex + 1)
    }, numSeconds * 1000);
  }
})();
.slideshow img {
  display: none;
  border: 1px solid black;
}
.slideshow .controls {
  max-width: 255px;
  text-align: center;
}
.slideshow .left {
  float: left;
  cursor: pointer;
}
.slideshow .right {
  float: right;
  cursor: pointer;
}
<div class="slideshow">
  <img src="http://placehold.it/250x150/000000/ffffff" />
  <img src="http://placehold.it/250x150/ff0000/ffffff" />
  <img src="http://placehold.it/250x150/00ff00/ffffff" />
  <img src="http://placehold.it/250x150/0000ff/ffffff" />
  <img src="http://placehold.it/250x150/ffffff/000000" />
  <div class="controls"> <span class="left">&lt;&lt;</span>
    <span class="current"></span>
    <span class="right">&gt;&gt;</span>
  </div>
</div>

有很多JavaScript库和jQuery扩展,你可以使用它们来获得更多的功能,而不必编写太多代码。我鼓励您探索已经开发的内容,以了解不同的实现。