需要使用 JavaScript 创建可点击的自动幻灯片

Need to create a clickable & automatic slideshow using JavaScript

我希望创建一个幻灯片放映,用户可以在其中单击到下一张幻灯片,而且如果没有 click 发生,幻灯片放映将自动移至下一张幻灯片。

我创建了下面的代码,如果 5 秒内没有点击,它会自动转到下一张幻灯片,但问题是当 prev next 按钮是 clicked 时,幻灯片随机开始在不到一秒的时间内彼此自动化??

我已经在网上寻找解决方案,但没有明确的答案:(

var slideIndex = 1;
showSlides(slideIndex);

function plusSlides(n) {

  showSlides(slideIndex += n);

}

function currentSlide(n) {

  showSlides(slideIndex = n);

}

function showSlides(n) {

  var i;

  var slides = document.getElementsByClassName("mySlides");

  if (n == undefined) {
    n = ++slideIndex
  }

  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";

  setTimeout(showSlides, 5000)

}
.mySlides {
  display: none;
}

.prev,
.next {
  cursor: pointer;
  position: absolute;
  top: 50%;
  width: auto;
  margin-top: -120px;
  padding-left: 10px;
  padding-right: px;
  padding-bottom: 10px;
  color: #A371D1;
  font-weight: bold;
  font-size: 60px;
  transition: 0.5s ease;
  border-radius: 0 15px 15px 0;
}

.next {
  right: 0px;
  border-radius: 15px 0px 0px 15px;
}

.prev:hover,
.next:hover {
  background-color: white;
}
<div id="slideShowContainer">

  <div class="mySlides fade3">

    <img class="homePageSlides" id="slidePic1" src="Purplelimetree-images/HomePage/aboutUs6.jpg">

  </div>

  <div class="mySlides fade3">

    <img class="homePageSlides" src="Purplelimetree-images/HomePage/manLookinAtTreeHouse.jpg">

  </div>

  <a class="prev" onclick="plusSlides(-1)">&lsaquo;</a>

  <a class="next" onclick="plusSlides(1)">&rsaquo;</a>


</div>

当用户与按钮交互时,您的超时需要被清除。如果不清除超时,它会自行 运行 而不管人工交互,它会弄乱您的幻灯片索引。

您的原始代码不会对任何按钮正常工作,因为您的时间将在 5 秒后开始触发,并且由于您从未清除它们,它会在您单击按钮时触发多次

https://jsfiddle.net/tssqtdp7/

var slideIndex = 1;
var t;

showSlides(slideIndex);

function plusSlides(n) {    
  slideIndex = slideIndex + n;
  clearTimeout(t);
  showSlides(slideIndex);
  console.log(slideIndex);
}

function currentSlide(n) {
  showSlides(slideIndex = n);
}

function showSlides(n) {

  var i;
  var slides = document.getElementsByClassName("mySlides");

  if (n == undefined) {
    n = ++slideIndex;
  }

  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";
  t = setTimeout(showSlides, 5000);
}