萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 全屏圖片畫廊帶縮略圖導航

效果

點擊縮略圖切換大圖全屏顯示,支援鍵盤左右鍵、滑鼠滾輪、觸控滑動、預載入。

核心預載入插件

(function($) {
    $.fn.preload = function(options) {
        var opts = $.extend({}, $.fn.preload.defaults, options);
        var count = this.length, loaded = 0;
        return this.each(function() {
            var src = $(this).attr('src');
            $('').on('load', function() {
                if (++loaded === count) opts.onComplete();
            }).attr('src', src);
        });
    };
    $.fn.preload.defaults = { onComplete: $.noop };
})(jQuery);

畫廊初始化邏輯

var $thumbs = $('#thumbnails img');
var $full = $('#fullscreen-img');

// 預載所有大圖
$thumbs.each(function() {
    var big = $(this).data('big');
    if (big) $('').attr('src', big);
}).preload({onComplete: initGallery});

function initGallery() {
    $thumbs.click(function() {
        var src = $(this).data('big') || this.src;
        $full.attr('src', src).fadeIn();
        $('#overlay').fadeIn();
    });

    $('#overlay').click(function() { $(this).fadeOut(); $full.fadeOut(); });
    $(document).keydown(function(e) {
        if (e.key === 'ArrowRight') next();
        if (e.key === 'ArrowLeft') prev();
    });
}

HTML 結構

<div id="thumbnails">
    <img src="thumb1.jpg" data-big="large1.jpg">
    <img src="thumb2.jpg" data-big="large2.jpg">
</div>
<div id="overlay"><img id="fullscreen-img"></div>

CSS:#overlay{position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,.9);display:none;text-align:center;} #fullscreen-img{max-width:90%;max-height:90%;margin-top:5vh;}

copyright © 萬盛學電腦網 all rights reserved