我的目标是在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();
答案 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(); }
}
}
现在工作正常!