使用javascript在最后一张图片停止我的滑块

时间:2017-02-19 13:27:28

标签: javascript slider

我是javascript的初学者,我正在寻找一个解决方案,在最后一张照片后停止我的滑块。以下代码显示了有关它的当前代码。大部分来自w3schools。

var slideIndex = 1;
showSlides(slideIndex);

function next_prev(n) {
  showSlides(slideIndex += n);
}

function startbild(){
  var slides = document.getElementsByClassName("mySlides");
  if(slides == 0){} else{
    slides[0].style.display = "block";
    for (i = 1; i < slides.length; i++) {
    slides[i].style.display = "none"; 
    document.getElementById("dia-shows").innerHTML = 1;
    }
  }
}

function showSlides(n) {
  var i;
  var slides = document.getElementsByClassName("mySlides");
  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";
  document.getElementById("dia-shows").innerHTML = slideIndex;
  document.getElementById("dia-gesamt").innerHTML = slides.length;
}

2 个答案:

答案 0 :(得分:1)

if (n > slides.length) {slideIndex = 1} //if last is reached, restart with first

应该是

if (n > slides.length) {slidesIndex=slides.length}  //if last is reached, stay at last

你也可以改变

function next_prev(n) {
 showSlides(slideIndex += n);
}

要:

function next_prev(n) {
 var slides = document.getElementsByClassName("mySlides");
 showSlides(slideIndex = Math.min(slideIndex+n,slides.length));
}

注意:w3schools推出糟糕的代码,请从MDN开始学习,有更好的+有更好的编码风格+更好的解释。所以这是一个改进的代码:

var slideIndex = 1;
var slides;// no need to redefine in every function

function init(){
    slides = document.getElementsByClassName("mySlides");//get the slides, store in variable
    if(!slides){
        return console.error("no slides..");
    }
    showSlides();//show the first time
    setInterval(next_prev,1000,1);//demo ( every 1000ms increase with 1)
}
window.onload=init;//if page loaded, init

function next_prev(n) {
    slideIndex=Math.max(Math.min(slideIndex+n,slides.length),1);// slidesIndex stays between slides.length and 1.
    showSlides();
 } 

function showSlides() {//no need to pass n, its equal to slideIndex
     for (var i = 0; i < slides.length; i++) {
        slides[i].style.display = "none"; //hide all
     }
    slides[slideIndex-1].style.display = "block";//show one
    document.getElementById("dia-shows").innerHTML = slideIndex;
    document.getElementById("dia-gesamt").innerHTML = slides.length;
}

- &GT; https://developer.mozilla.org/de/docs/Web/JavaScript

答案 1 :(得分:1)

我认为,您的代码不完整。您可以在问题发生的地方发布一个工作示例吗?

改变

if (n < 1) {slideIndex = slides.length}
if (n > slides.length) {slideIndex = 1} 

if (n < 1) {
  slideIndex = 1;
} else if (n > slides.length) {
  slideIndex = slides.length;
} else {
  slideIndex = n;
}

应该在两个方向上做你想做的事。

当第一帧或最后一帧可见时,您应该隐藏允许用户再次滑动的相关控件。

每当传递的n超出有效范围时,它就会被限制在该范围内。