• PhotoSwipe 图片浏览插件使用方法


    一、简介

    PhotoSwipe 是专为移动触摸设备设计的相册/画廊.兼容所有iPhone、iPad、黑莓6+,以及桌面浏览器.底层实现基于HTML/CSS/JavaScript,是一款免费开源的相册产品。

    官方网站:http://photoswipe.com/ 
    源码下载:https://github.com/dimsemenov/photoswipe 
    国内CDN:http://www.bootcdn.cn/photoswipe/

    二、使用

    1、新建html页面,如果是移动端看的话,需要在页面头部插入视口说明:

    <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no">
    

    2、引入 photoswipe.css、default-skin.css 文件,引入 photoswipe.js、photoswipe-ui-default.js 文件。

    <link href="http://cdn.bootcss.com/photoswipe/4.1.1/photoswipe.css" rel="stylesheet">
    <link href="http://cdn.bootcss.com/photoswipe/4.1.1/default-skin/default-skin.css" rel="stylesheet">
    <script src="http://cdn.bootcss.com/photoswipe/4.1.1/photoswipe.js"></script>
    <script src="http://cdn.bootcss.com/photoswipe/4.1.1/photoswipe-ui-default.js"></script>
    

    3、必要的HTML结构

    <div class="repairImgList lightgallery" data-pswp-uid="1" id="PhotoSwipe-demo">
    	<figure>
    		<div>
    			<a href="http://192.168.0.99:9090/wyglFile/images/overhaul/03d1150a24a74e87ba89f689f1c374a7-20160328110004.jpg" data-size="640x1136"><img src="http://192.168.0.99:9090/wyglFile/images/overhaul/03d1150a24a74e87ba89f689f1c374a7-20160328110004.jpg"></a>
    		</div>
    	</figure>
    	<figure>
    		<div>
    			<a href="http://192.168.0.99:9090/wyglFile/images/overhaul/03d1150a24a74e87ba89f689f1c374a7-20160328110004.jpg" data-size="640x1136"><img src="http://192.168.0.99:9090/wyglFile/images/overhaul/03d1150a24a74e87ba89f689f1c374a7-20160328110004.jpg"></a>
    		</div>
    	</figure>
    </div>
    

    4、必要的启动代码

    <!-- Root element of PhotoSwipe. Must have class pswp. -->
    <div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">
    	<!-- Background of PhotoSwipe.
    	It's a separate element as animating opacity is faster than rgba(). -->
    	<div class="pswp__bg"></div>
    	<!-- Slides wrapper with overflow:hidden. -->
    	<div class="pswp__scroll-wrap">
    		<!-- Container that holds slides.
    		PhotoSwipe keeps only 3 of them in the DOM to save memory.
    		Don't modify these 3 pswp__item elements, data is added later on. -->
    		<div class="pswp__container">
    			<div class="pswp__item"></div>
    			<div class="pswp__item"></div>
    			<div class="pswp__item"></div>
    		</div>
    		<!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
    		<div class="pswp__ui pswp__ui--hidden">
    			<div class="pswp__top-bar">
    				<!--  Controls are self-explanatory. Order can be changed. -->
    				<div class="pswp__counter"></div>
    				<button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
    				<button class="pswp__button pswp__button--share" title="Share"></button>
    				<button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
    				<button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>
    				<!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
    				<!-- element will get class pswp__preloader--active when preloader is running -->
    				<div class="pswp__preloader">
    					<div class="pswp__preloader__icn">
    						<div class="pswp__preloader__cut">
    							<div class="pswp__preloader__donut"></div>
    						</div>
    					</div>
    				</div>
    			</div>
    			<div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
    				<div class="pswp__share-tooltip"></div>
    			</div>
    			<button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
    			</button>
    			<button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
    			</button>
    			<div class="pswp__caption">
    				<div class="pswp__caption__center"></div>
    			</div>
    		</div>
    	</div>
    </div>
    

    这部分代码是相册组成的基本代码,由于PhotoSwipe没有集成到JS里面,所以需要手动的添加到body内,当然也可以采用JS方式把HTML代码拼接进去,我这里已经接好了,见下面JS:

    var gelleryHtml = "";
    gelleryHtml += "<div id='gallery' class='pswp' tabindex='-1' role='dialog' aria-hidden='true'>";
    gelleryHtml += "<div class='pswp__bg'></div>";
    gelleryHtml += "<div class='pswp__scroll-wrap'>";
    gelleryHtml += "<div class='pswp__container'>";
    gelleryHtml += "<div class='pswp__item'></div>";
    gelleryHtml += "<div class='pswp__item'></div>";
    gelleryHtml += "<div class='pswp__item'></div>";
    gelleryHtml += "</div>";
    gelleryHtml += "<div class='pswp__ui pswp__ui--hidden'>";
    gelleryHtml += "<div class='pswp__top-bar'>";
    gelleryHtml += "<div class='pswp__counter'></div>";
    gelleryHtml += "<button class='pswp__button pswp__button--close' title='Close (Esc)'></button>";
    gelleryHtml += "<button class='pswp__button pswp__button--share' title='Share' style='display:none'></button>";
    gelleryHtml += "<button class='pswp__button pswp__button--fs' title='Toggle fullscreen'></button>";
    gelleryHtml += "<button class='pswp__button pswp__button--zoom' title='Zoom in/out'></button>";
    gelleryHtml += "<div class='pswp__preloader'>";
    gelleryHtml += "<div class='pswp__preloader__icn'>";
    gelleryHtml += "<div class='pswp__preloader__cut'>";
    gelleryHtml += "<div class='pswp__preloader__donut'></div>";
    gelleryHtml += "</div>";
    gelleryHtml += "</div>";
    gelleryHtml += "</div>";
    gelleryHtml += "</div>";
    gelleryHtml += "<div class='pswp__share-modal pswp__share-modal--hidden pswp__single-tap'>";
    gelleryHtml += "<div class='pswp__share-tooltip'>";
    gelleryHtml += "</div>";
    gelleryHtml += "</div>";
    gelleryHtml += "<button class='pswp__button pswp__button--arrow--left' title='Previous (arrow left)'></button>";
    gelleryHtml += "<button class='pswp__button pswp__button--arrow--right' title='Next (arrow right)'></button>";
    gelleryHtml += "<div class='pswp__caption'>";
    gelleryHtml += "<div class='pswp__caption__center'>";
    gelleryHtml += "</div>";
    gelleryHtml += "</div>";
    gelleryHtml += "</div>";
    gelleryHtml += "</div>";
    gelleryHtml += "</div>";
    $(function() {
    	$('body').append(gelleryHtml);
    })
    

    5、最后,加上必要的启动代码:

    var initPhotoSwipeFromDOM = function(gallerySelector) {
    
        // 解析来自DOM元素幻灯片数据(URL,标题,大小...)
        // (children of gallerySelector)
        var parseThumbnailElements = function(el) {
            var thumbElements = el.childNodes,
                numNodes = thumbElements.length,
                items = [],
                figureEl,
                linkEl,
                size,
                item,
                divEl;
    
            for (var i = 0; i < numNodes; i++) {
    
                figureEl = thumbElements[i]; // <figure> element
    
                // 仅包括元素节点
                if (figureEl.nodeType !== 1) {
                    continue;
                }
                divEl = figureEl.children[0];
                linkEl = divEl.children[0]; // <a> element
    
                size = linkEl.getAttribute('data-size').split('x');
    
                // 创建幻灯片对象
                item = {
                    src: linkEl.getAttribute('href'),
                    w: parseInt(size[0], 10),
                    h: parseInt(size[1], 10)
                };
    
    
    
                if (figureEl.children.length > 1) {
                    // <figcaption> content
                    item.title = figureEl.children[1].innerHTML;
                }
    
                if (linkEl.children.length > 0) {
                    // <img> 缩略图节点, 检索缩略图网址
                    item.msrc = linkEl.children[0].getAttribute('src');
                }
    
                item.el = figureEl; // 保存链接元素 for getThumbBoundsFn
                items.push(item);
            }
    
            return items;
        };
    
        // 查找最近的父节点
        var closest = function closest(el, fn) {
            return el && (fn(el) ? el : closest(el.parentNode, fn));
        };
    
        // 当用户点击缩略图触发
        var onThumbnailsClick = function(e) {
            e = e || window.event;
            e.preventDefault ? e.preventDefault() : e.returnValue = false;
    
            var eTarget = e.target || e.srcElement;
    
            // find root element of slide
            var clickedListItem = closest(eTarget, function(el) {
                return (el.tagName && el.tagName.toUpperCase() === 'FIGURE');
            });
    
            if (!clickedListItem) {
                return;
            }
    
            // find index of clicked item by looping through all child nodes
            // alternatively, you may define index via data- attribute
            var clickedGallery = clickedListItem.parentNode,
                childNodes = clickedListItem.parentNode.childNodes,
                numChildNodes = childNodes.length,
                nodeIndex = 0,
                index;
    
            for (var i = 0; i < numChildNodes; i++) {
                if (childNodes[i].nodeType !== 1) {
                    continue;
                }
    
                if (childNodes[i] === clickedListItem) {
                    index = nodeIndex;
                    break;
                }
                nodeIndex++;
            }
    
    
    
            if (index >= 0) {
                // open PhotoSwipe if valid index found
                openPhotoSwipe(index, clickedGallery);
            }
            return false;
        };
    
        // parse picture index and gallery index from URL (#&pid=1&gid=2)
        var photoswipeParseHash = function() {
            var hash = window.location.hash.substring(1),
                params = {};
    
            if (hash.length < 5) {
                return params;
            }
    
            var vars = hash.split('&');
            for (var i = 0; i < vars.length; i++) {
                if (!vars[i]) {
                    continue;
                }
                var pair = vars[i].split('=');
                if (pair.length < 2) {
                    continue;
                }
                params[pair[0]] = pair[1];
            }
    
            if (params.gid) {
                params.gid = parseInt(params.gid, 10);
            }
    
            return params;
        };
    
        var openPhotoSwipe = function(index, galleryElement, disableAnimation, fromURL) {
            var pswpElement = document.querySelectorAll('.pswp')[0],
                gallery,
                options,
                items;
    
            items = parseThumbnailElements(galleryElement);
    
            // 这里可以定义参数
            options = {
                barsSize: {
                    top: 100,
                    bottom: 100
                },
                fullscreenEl: false,
                shareButtons: [{
                    id: 'wechat',
                    label: '分享微信',
                    url: '#'
                }, {
                    id: 'weibo',
                    label: '新浪微博',
                    url: '#'
                }, {
                    id: 'download',
                    label: '保存图片',
                    url: '{{raw_image_url}}',
                    download: true
                }],
    
                // define gallery index (for URL)
                galleryUID: galleryElement.getAttribute('data-pswp-uid'),
    
                getThumbBoundsFn: function(index) {
                    // See Options -> getThumbBoundsFn section of documentation for more info
                    var thumbnail = items[index].el.getElementsByTagName('img')[0], // find thumbnail
                        pageYScroll = window.pageYOffset || document.documentElement.scrollTop,
                        rect = thumbnail.getBoundingClientRect();
    
                    return {
                        x: rect.left,
                        y: rect.top + pageYScroll,
                        w: rect.width
                    };
                }
    
            };
    
            // PhotoSwipe opened from URL
            if (fromURL) {
                if (options.galleryPIDs) {
                    // parse real index when custom PIDs are used 
                    for (var j = 0; j < items.length; j++) {
                        if (items[j].pid == index) {
                            options.index = j;
                            break;
                        }
                    }
                } else {
                    // in URL indexes start from 1
                    options.index = parseInt(index, 10) - 1;
                }
            } else {
                options.index = parseInt(index, 10);
            }
    
            // exit if index not found
            if (isNaN(options.index)) {
                return;
            }
    
            if (disableAnimation) {
                options.showAnimationDuration = 0;
            }
    
            // Pass data to PhotoSwipe and initialize it
            gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, options);
            gallery.init();
        };
    
        // loop through all gallery elements and bind events
        var galleryElements = document.querySelectorAll(gallerySelector);
    
        for (var i = 0, l = galleryElements.length; i < l; i++) {
            galleryElements[i].setAttribute('data-pswp-uid', i + 1);
            galleryElements[i].onclick = onThumbnailsClick;
        }
    
        // Parse URL and open gallery if it contains #&pid=3&gid=1
        var hashData = photoswipeParseHash();
        if (hashData.pid && hashData.gid) {
            openPhotoSwipe(hashData.pid, galleryElements[hashData.gid - 1], true, true);
        }
    };
    

    三、DEMO展示及下载

    点击下载

  • 相关阅读:
    十三 .Django(ORM表高级操作)
    十二 .Django ForeighKey自关联(ORM)
    十二 .Django 一对多表ForeighKey(ORM)
    十一 .Django 一对一表OneToOneField (ORM)
    十 .Django 单表操作(ORM)
    八 .Django 模型(models)
    【模板】Lucas定理
    【模板】AC自动机加强版
    【模板】AC自动机
    【POJ3162】Walking Race 树形dp+单调队列+双指针
  • 原文地址:https://www.cnblogs.com/jone-chen/p/6108407.html
Copyright © 2020-2023  润新知