JavaScript >> Javascript 文檔 >  >> jQuery

jQuery 圖片幻燈片插件

一張漂亮的照片可以讓設計脫穎而出。但是我們在 Tutorialzine 意識到有時單張圖片是不夠的,您真正需要的是一張流暢的圖片幻燈片,以吸引用戶的注意力並為應用程序帶來動態。但是,此類幻燈片的實現有時會很棘手,因此我們決定製作一個小插件來為您完成這項工作。

工作原理

這真的很簡單!首先,您必須像往常一樣將圖像插入到 html 中。完成後,您必須添加一個數據屬性 - data-slideshow - 並將其值設置為您希望轉換為幻燈片的一系列圖像的路徑:

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

剩下的就是在你的頁面中包含我們的插件,調用它的 slideShow() 方法和你的幻燈片很不錯!

代碼

該插件由一個 JavaScript 文件和一個 CSS 文件組成。

我們將從 .js 文件開始!

assets/jQuery-slideshow-plugin/plugin.js

該文件包含一個常規的 jQuery 插件。首先我們需要定義我們的默認選項。

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

基本思想是我們從 data-slideshow 某個圖像的屬性並將它們插入到一個div中作為其背景。這個 div 具有原始圖片的尺寸,在它收集了幻燈片的所有圖像(包括我們開始使用的那個)之後替換它。讓我們看一下代碼,讓它更清晰一點。

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

}

激活後,圖像開始自動淡入淡出。
根據設置,我們還可以通過單擊和懸停來控制幻燈片。
感謝hammer.js,我們也可以滑動瀏覽圖片。

讓我們看看移動幻燈片的功能!

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

最後,讓我們快速瀏覽一下其中的一些 css。

assets/jQuery-slideshow-plugin/plugin.css

我們希望幻燈片的所有圖像相互堆疊,因此我們為它們提供了“滑動”類。它還使它們適合整個幻燈片 div。

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

然後我們將按鈕的 z-index 設置為 10,以將它們放在圖片的頂部。

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

最後,我們用 css 邊框製作三角形箭頭,並將它們放在 z-index 為 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;
}

使用插件

要使用該插件,請包含 assets/jQuery-slideshow-plugin/plugin.css 到頁面的頂部,以及 assets/jQuery-slideshow-plugin/plugin.js 在您複製 jQuery 和 Hammer.js 庫之後。

要初始化插件,請使用這段代碼並隨意更改設置的值。

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

完成!

有了這個,我們總結了教程。我們希望您能試用該插件。我們盡最大努力使其使用起來盡可能簡單和有趣,同時仍保持合理的功能。如有任何建議、問題和意見,請隨時在下方發表評論。


Tutorial JavaScript 教程
  1. 字符串操作

  2. WebAssembly (Wasm) 會取代 JavaScript 嗎?

  3. 開源:測試和審查靜態站點生成器(SSG)

  4. JavaScript 編碼挑戰

  5. 在 AWS 上部署網站

  6. // 讓我們在 Javascript 中學習 `this`

  7. 搜索要處理的 React 項目

  1. 如何在字符串中找到匹配單詞的確切數量?

  2. Medusa:創建快速且高度可定制的電子商務商店

  3. 術語定義,Eloquent Javascript

  4. 使用 jQuery val() 發送表單數據並使用 FormData 發送數據

  5. 使用 Headless Chrome 和 Vue CLI 3 運行 Nightwatch E2E 測試

  6. JavaScript 內部 - 垃圾回收

  7. 繼承人如何在 Android 設備上創建 React 應用程序

  1. 使用 Ionic React 實現暗/亮模式主題

  2. 如何使用 NextJS 和 Microlink Cards 為您的博客自動生成縮略圖

  3. 在基於 Electron 的應用程序中下載文件的選項有哪些?

  4. 當生活給你容器時,做 WebAppade!