Plugin jQuery Image Slideshow

Pěkná fotografie má daleko k tomu, aby design vynikl. Ale my v Tutorialzine jsme si uvědomili, že někdy jeden obrázek nestačí a to, co opravdu potřebujete, je plynulá prezentace obrázků, která upoutá pozornost uživatele a vnese do aplikace dynamiku. Implementace takovýchto prezentací však může být někdy ošemetná, proto jsme se rozhodli vytvořit malý plugin, který to udělá za vás.

Jak to funguje

Je to opravdu jednoduché! Nejprve musíte do html vložit obrázek, jak byste to normálně dělali. Poté musíte přidat datový atribut - data-slideshow - a nastavte jeho hodnotu na cestu k sérii obrázků, které chcete změnit na prezentaci:

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

Jediné, co zbývá, je zahrnout náš plugin do vaší stránky, zavolat jeho slideShow() a vaše prezentace je v pořádku!

Kodex

Plugin se skládá ze souboru JavaScript a souboru CSS.

Začneme souborem .js!

assets/jQuery-slideshow-plugin/plugin.js

Tento soubor obsahuje běžný plugin jQuery. Nejprve musíme definovat naše výchozí možnosti.

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);

Základní myšlenkou je, že přebíráme zdroje z data-slideshow atribut určitého obrázku a vložte je do prvku div jako jeho pozadí. Tento div má rozměry původního obrázku a poté, co shromáždí všechny obrázky pro snímky (včetně toho, se kterým jsme začínali), jej nahradí. Pojďme se podívat na kód, aby to bylo trochu jasnější.

// 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)

}

Po aktivaci se obrazy začnou jeden po druhém automaticky roztmívat a zeslabovat.
V závislosti na nastavení můžeme také ovládat prezentaci kliknutím a najetím.
Díky hammer.js jsme také umožnili procházet obrázky.

Pojďme se podívat na funkce, které pohybují snímky!

// 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));
        }
    })
}

Nakonec se pojďme rychle podívat na některé css.

assets/jQuery-slideshow-plugin/plugin.css

Chceme, aby se všechny obrázky pro naše snímky naskládaly na sebe, a proto jim přiřadíme třídu „sliding“. Díky tomu se také vejdou do celé sekce prezentace.

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

Poté tlačítkům nastavíme z-index 10, abychom je umístili na obrázky.

.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));
}

Nakonec z okrajů css vytvoříme trojúhelníkové šipky a dáme je navrch všeho se z-indexem 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;
}

Pomocí pluginu

Chcete-li plugin použít, zahrňte assets/jQuery-slideshow-plugin/plugin.css do záhlaví stránky a assets/jQuery-slideshow-plugin/plugin.js po vaší kopii knihoven jQuery a Hammer.js.

K inicializaci pluginu použijte tento kus kódu a klidně změňte hodnoty nastavení.

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

Hotovo!

Tímto jsme tutoriál uzavřeli. Doufáme, že plugin vyzkoušíte. Udělali jsme maximum pro to, aby bylo používání co nejjednodušší a nejzábavnější, a přitom zachovali rozumnou funkčnost. V případě jakýchkoli doporučení, otázek a názorů neváhejte zanechat komentář níže.