Carrusel de tarjetas automáticas en Vanilla JavaScript-Vanilla-IMG-Slideshow
| Autor: | JHerbranson |
|---|---|
| Views Total: | 582 |
| Sitio oficial: | Ir a la web |
| Actualizado: | November 3, 2018 |
| Licencia: | MIT |
Vista prévia
Descripción
Una proyección de diapositivas de imagen automática en JavaScript vainilla que recorre un grupo de imágenes al igual que una tarjeta. Animaciones suaves basadas en transformaciones y transiciones CSS3.
Funcionamiento
Inserte un grupo de imágenes en la proyección de diapositivas.
<div id="mySlideshow"> <img class="gallery-item" src="1.jpg" alt="pic1"> <img class="gallery-item" src="2.jpg" alt="pic2"> <img class="gallery-item" src="3.jpg" alt="pic3"> <img class="gallery-item" src="4.jpg" alt="pic4"> <img class="gallery-item" src="5.jpg" alt="pic5"> ... </div>
Las reglas de CSS/CSS3 necesarias para la proyección de diapositivas.
#mySlideshow {
margin: 50px auto 0;
max-width: 600px;
height: 300px;
position: relative;
overflow: hidden;
}
img {
transform: translate(600px);
position: absolute;
width: 100%;
}
.showcase-img {
transform: translate(0);
transition: .6s;
}
.showcase-left {
transform: translate(-600px);
transition: .6s;
} El principal JavaScript para habilitar la proyección de diapositivas.
const images = document.querySelectorAll(".gallery-item");
let timmer = setInterval(cycleImage, 4000);
// Will always stay the same
const length = images.length;
// Will increment by one everytime the function is called.
let imageCounter = images.length;
// e.g. 3 % 3 = 0, 4 % 3 = 1, 5 % 3 = 2, etc.
// loops through the array like this, using the remainder as the index number
function cycleImage() {
//the new item in the array shown
let newIndex = imageCounter % length;
//the previous item in the array
let lastIndex = 0;
newIndex === 0 ? lastIndex = length - 1 : lastIndex = newIndex - 1;
//the item before lastIndex
//moves it back to rest on the right side
let moveIndexRight = 0;
lastIndex === 0 ? moveIndexRight = length - 1 : moveIndexRight = lastIndex - 1;
images[newIndex].classList.add("showcase-img");
images[lastIndex].classList.remove("showcase-img");
images[lastIndex].classList.add("showcase-left");
images[moveIndexRight].classList.remove("showcase-left");
imageCounter++;
}
cycleImage();





