添加播放/暂停按钮到图像滑块

时间:2018-05-24 14:04:50

标签: javascript animation

我正在尝试向我的图像查看器添加播放和暂停按钮。我有next和prev按钮工作正常,但我喜欢在我的JavaScript中集成一个播放和暂停按钮。

有人可以帮忙吗?

以下是通过链接Demo

的工作演示

脚本:

<div class="w3-container">

</div>

<div class="w3-content" style="max-width:800px">
<img class="mySlides" src="http://www.chorleyweather.com/forecast-charts/ecmwfcharts/na500hpa_1.png" style="width:95%"></li>
<img class="mySlides" src="http://www.chorleyweather.com/forecast-charts/ecmwfcharts/na500hpa_2.png" style="width:95%"></li>


</div>


  <div class="w3-section">
    <button class="w3-btn" onclick="plusDivs(-1)"><h6> Prev Image<h6/></button>
    <button class="w3-btn" onclick="plusDivs(1)"><h6>Next Image<h6/> </button><h6/>
  </div>
</div>




<script>
var slideIndex = 1;
showDivs(slideIndex);

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

function currentDiv(n) {
  showDivs(slideIndex = n);
}

function showDivs(n) {
  var i;
  var x = document.getElementsByClassName("mySlides");
  var dots = document.getElementsByClassName("demo");
  if (n > x.length) {slideIndex = 1}
  if (n < 1) {slideIndex = x.length}
  for (i = 0; i < x.length; i++) {
     x[i].style.display = "none";
  }
  for (i = 0; i < dots.length; i++) {
     dots[i].className = dots[i].className.replace(" w3-red", "");
  }
  x[slideIndex-1].style.display = "block";
  dots[slideIndex-1].className += " w3-red";
}

window.onload = function() {
    var image = document.getElementById("img");

    function updateImage() {
        image.src = image.src.split("?")[0] + "?" + new Date().getTime();
    }

    setInterval(updateImage, 1000);
}
</script>

1 个答案:

答案 0 :(得分:0)

一种方法是使用布尔值来确定它是否应该播放,以及一个改变该布尔值的按钮。

按钮:

<button id="playpause"></button>

更新了window.onload = function

window.onload = function() {
    var image = document.getElementById("img");

    var playing = true;

    function updateImage() {
        if (playing) {
            image.src = image.src.split("?")[0] + "?" + new Date().getTime();
        }
    }

    var playpause = document.getElementById("playpause");
    playpause.onclick = function() {
        if (playing) {
            playing = false;
        } else {
            playng = true;
        }
    };


    setInterval(updateImage, 1000);
}

没有尝试过,但它应该可以解决问题。