自动播放不适用于我的Javascript滑块

时间:2019-06-10 21:44:13

标签: javascript

我的目标是在Javascript中编写一个内含Class的滑块。但我遇到2个问题:

  • 自动播放不起作用
  • 如果我单击“暂停”按钮,然后再次单击“播放”按钮,则自动播放也不起作用

HTML页面位于此处: http://p4547.phpnet.org/bikes/slider.html

这是我的Javascript代码:

class Diaporama {
  constructor() {
    this.controls = document.querySelectorAll('.controls');
    this.slides = document.querySelectorAll('#diaporama .slide');
    this.currentSlide = 0;
    this.n = null;
    this.playing = true;
    this.pauseButton = document.getElementById('pause');
    this.next = document.getElementById('next');
    this.previous = document.getElementById('previous');
  }

// Afficher les boutons previous, play, pause, next :
  controlling() {
    for(let i=0; i < this.controls.length; i++){
        this.controls[i].style.display = 'inline-block';
    }
  }

// Slider Automatique :
  goToSlide(n) {
    this.slides[this.currentSlide].className = 'slide';
    this.currentSlide = (n + this.slides.length)%this.slides.length;
    this.slides[this.currentSlide].className = 'slide showing';
    console.log(this.currentSlide);
  }

  nextSlide() {
    this.goToSlide(this.currentSlide + 1);
  }

  previousSlide() {
    this.goToSlide(this.currentSlide - 1);
  }

  slideInterval() {
    setInterval(this.nextSlide,5000);
  }

  pauseSlideshow() {
    this.pauseButton.innerHTML = '<i class="fas fa-play"></i>';
    this.playing = false;
    clearInterval(this.slideInterval);
  }

  playSlideshow() {
    this.pauseButton.innerHTML = '<i class="fas fa-pause"></i>';
    this.playing = true;
    this.slideInterval = setInterval(this.nextSlide,5000);
  }

  nextItem() {
  next.onclick = () => {
    this.pauseSlideshow();
    this.nextSlide();
  }
  }

  previousItem() {
    previous.onclick = () => {
      this.pauseSlideshow();
      this.previousSlide();
    }
  }

// Changement de slide par les touches du clavier :
  clickKeyboard() {
    document.addEventListener("keydown", ({keyCode}) => {
      if(keyCode === 37){
          this.nextSlide();
      }
      else if(keyCode === 39){
          this.previousSlide();
      }
  })
}

};

let slider = new Diaporama();
slider.controlling();
slider.goToSlide(0);
slider.nextSlide();
slider.previousSlide();
slider.pauseSlideshow();
slider.playSlideshow();
slider.nextItem();
slider.previousItem();
slider.clickKeyboard();

2 个答案:

答案 0 :(得分:1)

此问题位于playslideShow内部。在setInterval内调用this.nextSlide时,this的范围已更改。 this指的是窗口。

在这种情况下,可以使用bind()来确保它引用了滑块对象:

playSlideshow() {
    this.pauseButton.innerHTML = '<i class="fas fa-pause"></i>';
    this.playing = true;
    this.slideInterval = setInterval(this.nextSlide.bind(this),5000);
}

答案 1 :(得分:0)

哦,不,对不起,我发现了为什么我的“暂停”按钮有问题。 我刚刚添加了一个新功能:

  restart() {
      this.pauseButton.onclick = () => {
      if(this.playing){ this.pauseSlideshow(); }
      else{ this.playSlideshow(); }
    }
  }

现在工作正常!