如何将自动播放添加到图像滑块javascript中



我得到了这个开源滑块,我已经重写并调整了javascript代码的一些部分,以满足我的需要。

但我无法根据自己的愿望进行调整的是,让滑块在页面加载时自动播放图像或幻灯片。

const galleryContainer = document.querySelector('.gallery-container');
const galleryControlsContainer = document.querySelector('.gallery-controls');
const galleryControls = ['previous', 'add', 'next'];
const galleryItems = document.querySelectorAll('.gallery-item');
class Carousel {
constructor(container, items, controls) {
this.carouselContainer = container;
this.carouselControls = controls;
this.carouselArray = [...items];
}
updateGallery() {
this.carouselArray.forEach(el => {
el.classList.remove('gallery-item-1');
el.classList.remove('gallery-item-2');
el.classList.remove('gallery-item-3');
el.classList.remove('gallery-item-4');
el.classList.remove('gallery-item-5');
});
this.carouselArray.slice(0, 5).forEach((el, i) => {
el.classList.add(`gallery-item-${i+1}`);
});
}
setCurrentState(direction) {
if (direction.className == 'gallery-controls-previous') {
this.carouselArray.unshift(this.carouselArray.pop());
} else {
this.carouselArray.push(this.carouselArray.shift());
}

this.updateGallery();
}

setControls() {
this.carouselControls.forEach(control => {

if(control == 'add'){
}
else if(control == 'previous'){
let img = document.createElement('img');
img.src = "assets/images/icon_prev.png";
galleryControlsContainer.appendChild(img).className = `gallery-controls-${control}`;
galleryControlsContainer.appendChild(img).id = `mr40`;
}
else if(control == 'next'){
let img = document.createElement('img');
img.src = "assets/images/icon_next.png";
galleryControlsContainer.appendChild(img).className = `gallery-controls-${control}`;
}

});
}

useControls() {
const triggers = [...galleryControlsContainer.childNodes];
triggers.forEach(control => {
control.addEventListener('click', e => {
e.preventDefault();
if (control.className == 'gallery-controls-add') {} else {
this.setCurrentState(control);
}
});
});
}
}
const exampleCarousel = new Carousel(galleryContainer, galleryItems, galleryControls);
exampleCarousel.setControls();
exampleCarousel.useControls();

这就是上面的javascript。

下面是一个示例html

<!DOCTYPE html>
<html>
<head>
<title>slider</title>
<link rel="stylesheet" href="slider.css">
</head>
<body>

<div class="gallery">
<div class="gallery-container">
<img class="gallery-item gallery-item-1" src="cimg1.jpg" data-index="1">
<img class="gallery-item gallery-item-2" src="cimg2.jpg" data-index="2">
<img class="gallery-item gallery-item-3" src="cimg3.jpg" data-index="3">
</div>
<div class="gallery-controls"></div>
</div>

<script src="slider.js"></script>
</body>
</html>

所以,我很高兴有人帮忙。谢谢

我看到在构造对象时传递options(在本例中为滑块(。在您的情况下,选项将包括autoplay: booleanslideDelay: number或类似的内容。

添加功能应该像使用setTimeoutsetInterval一样简单,以便为滑块执行next功能。因此,它不会对鼠标单击进行操作,而是对间隔计时器进行操作。

https://developer.mozilla.org/en-US/docs/Web/API/setInterval

相关内容

  • 没有找到相关文章

最新更新