首页 > 解决方案 > 纯 Javascript 超级简单的幻灯片图像编号计数器?

问题描述

问题是我想在图像幻灯片下方实现一个幻灯片计数器,说明当前幻灯片编号与幻灯片总数,例如“1 of 3”等。

作为一个完整的 javascript 新手,我正在努力寻找适用于我已实现的现有代码的东西。— 希望能帮助您找到解决方案并实施幻灯片计数器

我使用了一些纯 javascript 从 w3 学校示例中提取的图像幻灯片,效果很好,示例可以在这里找到。(非常希望保持下一个/上一个功能相同,即光标单击图像的左/右)

https://jsfiddle.net/TEK22/1s205La6/

.project {
  position: relative;
  padding: 5% 20% 5% 20%;
  font-family: helvetica, sans-serif;
  font-size: 2em;
}

.imgslide img {
  width: 100%;
}

.prev {
  cursor: zoom-out;
  position: absolute;
  right: 50%;
  height: 100%;
  width: 50%;
}

.next {
  cursor: zoom-in;
  position: absolute;
  left: 50%;
  height: 100%;
  width: 50%;
}
<div class="project">
	<div class="prev" onclick="plusDivs(-1)"></div>
	<div class="next" onclick="plusDivs(1)"></div>
	<div class="imgslide noselect">
	    <img class="slides" src="https://i.imgur.com/Xhu0Qz8.png">
	    <img class="slides" src="https://i.imgur.com/arLyQDw.jpg">
	    <img class="slides" src="https://i.imgur.com/tbpcx4i.png">
	</div>
</div>

<script>

	var slideIndex = 1;
showDivs(slideIndex);

function plusDivs(n) {
  showDivs(slideIndex += n);
}

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

标签: javascripthtmlimagewebslideshow

解决方案


您想要实现的只是在这样slideIndexx.length分页区域中显示?

  1. 添加<div class="pagination"><div>到html代码。
  2. 添加document.getElementsByClassName("pagination")[0].innerText = slideIndex + ' of ' + x.length;到脚本。

.project {
  position: relative;
  padding: 5% 20% 5% 20%;
  font-family: helvetica, sans-serif;
  font-size: 2em;
}

.imgslide img {
  width: 100%;
}

.prev {
  cursor: zoom-out;
  position: absolute;
  right: 50%;
  height: 100%;
  width: 50%;
}

.next {
  cursor: zoom-in;
  position: absolute;
  left: 50%;
  height: 100%;
  width: 50%;
}
<div class="project">
	<div class="prev" onclick="plusDivs(-1)"></div>
	<div class="next" onclick="plusDivs(1)"></div>
	<div class="imgslide noselect">
	    <img class="slides" src="https://i.imgur.com/Xhu0Qz8.png">
	    <img class="slides" src="https://i.imgur.com/arLyQDw.jpg">
	    <img class="slides" src="https://i.imgur.com/tbpcx4i.png">
	</div>
  <div class="pagination"><div>
</div>

<script>

	var slideIndex = 1;
showDivs(slideIndex);

function plusDivs(n) {
  showDivs(slideIndex += n);
}

function showDivs(n) {
  var i;
  var x = document.getElementsByClassName("slides");
  if (n > x.length) {slideIndex = 1}    
  if (n < 1) {slideIndex = x.length}
  for (i = 0; i < x.length; i++) {
     x[i].style.display = "none";  
  }
  x[slideIndex-1].style.display = "block";  
  document.getElementsByClassName("pagination")[0].innerText = slideIndex + ' of ' + x.length;
}
</script>


推荐阅读