h5制作微信朋友圈点击大图

需要做一个类似微信朋友圈点击照片显示大图, 并且可以左右滑动查看其它图片的效果.


在网上学习了很多例子, 最终决定根据提供在路上的愚人同学的demo的来修改.

首先是photoswipe插件. 可以在github下载.

使用方法:

1. 先引入相关的js和css

<link rel="stylesheet prefetch" href="css/photoswipe.css">
<link rel="stylesheet prefetch" href="css/default-skin/default-skin.css">
<script src="js/photoswipe.js"></script>
<script src="js/photoswipe-ui-default.min.js"></script>

2. 加入pswp模板

实现这个组件, 需要在页面上用到一套pswp的class, 里面包含了点击大图时底下的蒙版, 还有左右滑动的控件, 以及大图的container, 总之就是必须要有的一套dom结构. 由于坐着没有把它写到js里, 所以要自己手动添加到需要打开图片的html页面里. 也可以自己封装起来.

它在图片尚未打开相册前没有任何行为, 所以直接加在页面中完全没问题.最好是加在页面的最底部最后一个div的后面. 不在任何一个有页面行为的div里. 我这次是把封在了一个js里加在了最后面即之前

<!-- 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>

                <!-- 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>

3.调整样式结构

在需要点击放大的图片画廊上, 加入如下结构

<div class="my-gallery clearfix" data-pswp-uid="1">
    <figure><div>
        <a href="images/share-0.jpeg" data-size="">
            <img class="lazy" src="images/share-0.jpeg">
        </a></div>
        <figcaption style="display:none;">这里可以加入图片描述</figcaption>
    </figure>
    <figure><div>
        <a href="images/share-0.jpeg" data-size="">
            <img class="lazy" src="images/share-0.jpeg">
        </a></div>
        <figcaption style="display:none;">这里可以加入图片描述</figcaption>
    </figure>
    <figure><div>
        <a href="images/share-0.jpeg" data-size="">
            <img class="lazy" src="images/share-0.jpeg">
        </a></div>
        <figcaption style="display:none;">这里可以加入图片描述</figcaption>
    </figure>
</div>

.my-gallery和底下入figure的样式自己根据需要在样式表中完成就可以了, 没有任何限制. 这里展示的是图片小图状态时的样式
.my-gallery里面的data-pswp-uid是一个唯一的值, 每个.my-gallery结构里都不一样
其中,标签里的是原图, 里面还有一项data-size的设置,是必须要有的. 如果缺少这个属性, 就无法成功. 我这里的data-size是用jQuery函数将它设置成了自动适应图片的宽高. 如果前端在展示大图的时候有切图的需要, 也可以将它固定写死在页面上. 如 data-size="600x700". 注意我这里写的是x不是*号

4. 调用photoswipe.js

我这里是直接在demo上拿来用了. 唯一的区别就是, 我多加了一个宽高的取值.就是自动给data-size赋值, 使得图片打开时是自适应的.

//图片画廊插件

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

/*打开画廊photoswipe*/ 
$(function(){

    window.onload=function(){
        auto_data_size();
    };

    
        //晒单大图宽度自适应
            function auto_data_size(){
                var imgss= $("figure img");
                $("figure img").each(function() {
                    var imgs = new Image();
                    imgs.src=$(this).attr("src");
                    var w = imgs.width,
                    h =imgs.height;
                    $(this).parent("a").attr("data-size","").attr("data-size",w+"x"+h);
                })
             };

            // auto_data_size();
    
            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 : 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 );
                    }
                    };
                
                    // execute above function
                    initPhotoSwipeFromDOM('.my-gallery');
                
                    
                    // $(".my-gallery>figure>div").each(function(){
                    // 	$(this).height($(this).width());
                    // });
                    
    
        })
        

因为借鉴了大量的别人的代码, 如果有问题的话请告知我, 我会删掉.

posted @ 2017-10-19 18:57  DarthBadwolf  阅读(454)  评论(0编辑  收藏  举报