纯Javascript超级简单的幻灯片图像编号计数器?

时间:2018-08-11 15:30:10

标签: javascript html image web slideshow

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

作为一个完整的javascript新手,我正在努力寻找与我已经实现的现有代码兼容的东西。 —非常感谢您找到解决方案并实施幻灯片计数器的帮助

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

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>

1 个答案:

答案 0 :(得分:0)

您想要实现的只是在分页区域显示slideIndex中的x.length

  1. 在HTML代码中添加<div class="pagination"><div>
  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>