Complemento de presentación de imágenes jQuery

Una buena foto contribuye en gran medida a que un diseño se destaque. Pero en Tutorialzine nos dimos cuenta de que a veces una sola imagen no es suficiente y lo que realmente necesita es una presentación de diapositivas fluida de imágenes para captar la atención del usuario y aportar dinamismo a la aplicación. Sin embargo, la implementación de tales presentaciones de diapositivas a veces puede ser complicada, por lo que decidimos crear un pequeño complemento para que haga el trabajo por usted.

Cómo funciona

¡Es realmente simple! Primero, debe insertar una imagen en el html como lo haría normalmente. Una vez hecho esto, debe agregar un atributo de datos:data-slideshow - y establezca su valor para que sea la ruta de una serie de imágenes que le gustaría convertir en una presentación de diapositivas:

<img src="...." data-slideshow="img1.jpg|img2.jpg|img3.jpg" />

Todo lo que queda es incluir nuestro complemento en su página, llame a su slideShow() método y su presentación de diapositivas está lista!

El Código

El complemento consta de un archivo JavaScript y uno CSS.

¡Comenzaremos con el archivo .js!

activos/jQuery-slideshow-plugin/plugin.js

Este archivo contiene un complemento jQuery regular. En primer lugar, debemos definir nuestras opciones predeterminadas.

options = $.extend({
    timeOut: 3000, // how long each slide stays on screen
    showNavigation: true, // show previous/next arrows
    pauseOnHover: true, // pause when hovering with the mouse
    swipeNavigation: true // (basic) support for swipe gestures
}, options);

La idea básica es que tomamos las fuentes del data-slideshow atributo de una determinada imagen e insertarlos en un div como fondo. Este div tiene las dimensiones de la imagen original y, una vez que ha recopilado todas las imágenes de las diapositivas (incluida la que empezamos), la reemplaza. Veamos el código para que quede un poco más claro.

// Variables
var intervals = [],
    slideshowImgs = [],
    originalSrc,
    img,
    cont,
    width,
    height,

// Creates an object with all the elements with a 'data-slideshow' attribute

container = this.filter(function () {
    return $(this).data('slideshow');
});

// Cycle through all the elements from the container object
// Later on we'll use the "i" variable to distinguish the separate slideshows from one another

for (var i = 0; i < container.length; i++) {

    cont = $(container[i]);

    width = container.eq(i).outerWidth(true);
    height = container.eq(i).outerHeight(true);

    // For every separate slideshow, create a helper <div>, each with its own ID.
    // In those we'll store the images for our slides.

    var helpdiv = $('<div id="slideshow-container-' + i + '" class="slideshow" >');

    helpdiv.height(height);
    helpdiv.width(width);

    // If this option is enabled, call a function that appends buttons

    if (options.showNavigation) {
        createNavigation();
    }

    // Append the original image to the helper <div>

    originalSrc = cont.attr('src');
    img = $('<div class="slide" style="background-image: url(' + originalSrc + ')">');
    img.appendTo(helpdiv);

    // Append the images from the data-slideshow attribute

    slideshowImgs[i] = cont.attr('data-slideshow').split("|");

    for (var j = 0; j < slideshowImgs[i].length; j++) {

        img = $('<div class="slide" style="background-image: url(' + slideshowImgs[i][j] + ')">');
        img.appendTo(helpdiv);

    }

    // Replace the original element with the helper <div>

    cont.replaceWith(helpdiv);

    // Activate the slideshow

    automaticSlide(i)

}

Tras la activación, las imágenes comienzan a aparecer y desaparecer una detrás de otra automáticamente.
Dependiendo de la configuración, también podemos controlar la presentación de diapositivas haciendo clic y pasando el mouse.
Gracias a hammer.js también hicimos posible deslizar las imágenes.

¡Veamos las funciones que mueven las diapositivas!

// Slideshow auto switch

function automaticSlide(index) {

    // Hide all the images except the first one
    $('#slideshow-container-' + index + ' .slide:gt(0)').hide();

    // Every few seconds fade out the first image, fade in the next one,
    // then take the first and append it to the container again, so it becomes last

    intervals[index] = setInterval(function () {
            $('#slideshow-container-' + index + ' .slide:first').fadeOut("slow")
                .next('.slide').fadeIn("slow")
                .end().appendTo('#slideshow-container-' + index + '');
        },
        options.timeOut);
}

// Pause on hover and resume on mouse leave

if (options.pauseOnHover) {
    (function hoverPause() {
        $('.slideshow').on({
            'mouseenter.hover': function () {
                clearInterval(intervals[($(this).attr('id').split('-')[2])])
            },
            'mouseleave.hover': function () {
                automaticSlide($(this).attr('id').split('-')[2])
            }
        });
    })()
}

// We use this to prevent the slideshow from resuming once we've stopped it

function hoverStop(id) {
    $('#' + id + '').off('mouseenter.hover mouseleave.hover');
}

// Create the navigation buttons

function createNavigation() {

    // The buttons themselves
    var leftArrow = $('<div class="leftBtn slideBtn hide">');
    var rightArrow = $('<div class="rightBtn slideBtn hide">');

    // Arrows for the buttons
    var nextPointer = $('<span class="pointer next"></span>');
    var prevPointer = $('<span class="pointer previous"></span>');

    prevPointer.appendTo(leftArrow);
    nextPointer.appendTo(rightArrow);

    leftArrow.appendTo(helpdiv);
    rightArrow.appendTo(helpdiv);
}

// Slideshow manual switch

if (options.showNavigation) {

// This shows the navigation when the mouse enters the slideshow
// and hides it again when it leaves it

    $('.slideshow').on({
        'mouseenter': function () {
            $(this).find('.leftBtn, .rightBtn').removeClass('hide')
        },
        'mouseleave': function () {
            $(this).find('.leftBtn, .rightBtn').addClass('hide')
        }
    });

    // Upon click, stop the automatic slideshow and change the slide

    $('.leftBtn').on('click', function () {

        // Clear the corresponding interval to stop the slideshow
        //  ( intervals is an array, so we give it the number of the slideshow container)

        clearInterval(intervals[($(this).parent().attr('id').split('-')[2])]);

        // Make the last slide visible and set it as first in the slideshow container

        $(this).parent().find('.slide:last').fadeIn("slow")
            .insertBefore($(this).parent().find('.slide:first').fadeOut("slow"));

        hoverStop($(this).parent().attr('id'));
    });

    $('.rightBtn').on('click', function () {

        // Clear the corresponding interval to stop the slideshow
        clearInterval(intervals[($(this).parent().attr('id').split('-')[2])]);

        // Fade out the current image and append it to the parent, making it last
        // Fade in the next one

        $(this).parent().find('.slide:first').fadeOut("slow")
            .next('.slide').fadeIn("slow")
            .end().appendTo($(this).parent());

        hoverStop($(this).parent().attr('id'));
    });
}

// Change slide on swipe

// Same as the 'on click' functions, but we use hammer.js this time

if (options.swipeNavigation) {
    $('.slideshow').hammer().on({
        "swiperight": function () {
            clearInterval(intervals[($(this).attr('id').split('-')[2])]);

            $(this).find('.slide:last').fadeIn("slow")
                .insertBefore($(this).find('.slide:first').fadeOut("slow"))

        },
        "swipeleft": function () {
            clearInterval(intervals[($(this).attr('id').split('-')[2])]);

            $(this).find('.slide:first').fadeOut("slow")
                .next('.slide').fadeIn("slow")
                .end().appendTo($(this));
        }
    })
}

Finalmente, echemos un vistazo rápido a algunos de los css.

activos/jQuery-slideshow-plugin/plugin.css

Queremos que todas las imágenes de nuestras diapositivas se apilen unas sobre otras, así que les damos la clase "deslizante". También hace que se ajusten a todo el div de la presentación de diapositivas.

.sliding {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-position: center;
    background-size: cover;
}

Luego, establecemos un índice z de 10 en los botones para colocarlos encima de las imágenes.

.slideBtn {
    position: absolute;
    z-index: 10;
    width: 50px;
    height: 100%;
    cursor: pointer;
}

.leftBtn {
    left: 0px;
    background: linear-gradient(to right, rgba(0, 0, 0, 0.4), rgba(0, 0, 0, 0));
}

.rightBtn {
    right: 0px;
    background: linear-gradient(to left, rgba(0, 0, 0, 0.4), rgba(0, 0, 0, 0));
}

Por último, creamos flechas triangulares con bordes css y las colocamos encima de todo con un índice z de 9001;

.pointer {
    position: absolute;
    top: 50%;
    margin-top: -32px;
    z-index: 9001;
    left: 12px;
    opacity: 0.8;
}

.previous {
    width: 0;
    height: 0;
    border-top: 20px solid transparent;
    border-bottom: 20px solid transparent;
    border-right: 20px solid white;

}

.next {
    width: 0;
    height: 0;
    border-top: 20px solid transparent;
    border-bottom: 20px solid transparent;
    border-left: 20px solid white;
    right: 12px;
    left: auto;
}

Uso del complemento

Para usar el complemento, incluya assets/jQuery-slideshow-plugin/plugin.css al encabezado de su página y assets/jQuery-slideshow-plugin/plugin.js después de su copia de las bibliotecas jQuery y Hammer.js.

Para inicializar el complemento, use este fragmento de código y siéntase libre de cambiar los valores de configuración.

(function ($) {
$('#activate').on('click', function () {
    $('img').slideShow({
        timeOut: 2000,
        showNavigation: true,
        pauseOnHover: true,
        swipeNavigation: true
    });
}(jQuery));

¡Listo!

Con esto redondeamos el tutorial. Esperamos que le des una oportunidad al complemento. Hicimos todo lo posible para que fuera lo más fácil y divertido de usar posible, manteniendo al mismo tiempo una funcionalidad razonable. Para cualquier recomendación, pregunta u opinión, no dude en dejar un comentario a continuación.