我在这里有一张图片幻灯片,带有原型设计。有些事情是错的,我无法解决它。我理解在setInterval中上下文丢失了,我尝试绑定它,但它不起作用。也尝试包装,但它也没有工作。我该怎么办呢?
function Slide() {
this.currentStep = 0;
this.time = 2000;
this.images = [];
this.images[0] = 'images/image1.jpg';
this.images[1] = 'images/image2.jpg';
this.images[2] = 'images/image3.jpg';
this.images[3] = 'images/image4.jpg';
this.images[4] = 'images/image5.jpg';
}
Slide.prototype.carousel = function() {
document.querySelector('.image').src = this.images[this.currentStep];
this.currentStep < this.images.length - 1 ? this.currentStep += 1 : this.currentStep = 0;
setInterval(carousel.bind(Slide), this.time);
}
const imageSlide = new Slide();
imageSlide.carousel();
&#13;
<div class="slide">
<img class="image" width="1000" height="500" alt="image">
</div>
&#13;
答案 0 :(得分:1)
您的代码有三个问题:
carousel
不存在。也许您的意思是Slide.prototype.carousel
,或者如果在函数内使用this.carousel
。Slide
,而不是绑定构造函数this
。this.carousel
传递给setInterval
,因此将以异步方式递归执行该函数。但是,并不像预期的那样,因为在每次执行时,您都会创建越来越多的重复上述内容。请改用setTimeout
。<强>段:强>
function Slide() {
this.currentStep = 0;
this.time = 2000;
this.images = [
'images/image1.jpg',
'images/image2.jpg',
'images/image3.jpg',
'images/image4.jpg',
'images/image5.jpg'
];
}
Slide.prototype.carousel = function() {
document.querySelector('.image').src = this.images[this.currentStep];
this.currentStep < this.images.length - 1
? this.currentStep += 1
: this.currentStep = 0;
setTimeout(this.carousel.bind(this), this.time);
}
const imageSlide = new Slide();
imageSlide.carousel();
&#13;
<div class="slide">
<img class="image" width="1000" height="500" alt="image">
</div>
&#13;
答案 1 :(得分:0)
您可以使用element.slider(sliderInterval)
Element.prototype.slider = function(slideInterval) {
let currentStep = 1;
let data = ['https://i.imgur.com/mcr23np.jpg', 'https://i.imgur.com/Eql027R.jpg', 'https://i.imgur.com/oUizZe6.jpg'];
let imageElement = this.getElementsByClassName('image')[0];
imageElement.src = data[0];
setInterval(() => {
imageElement.src = data[currentStep % data.length];
currentStep++;
}, slideInterval);
}
const mySlider = document.getElementById('mySlider');
mySlider.slider(4000);
&#13;
<div id="mySlider">
<img class="image" alt="Falied To Load" />
</div>
&#13;