欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

仿微信朋友圈图片点击放大效果

程序员文章站 2022-05-12 22:56:59
...

这两天写了个小项目,其中用到了点击一组图片中的一张可以查看它的放大版,用手向左滑动能看到下一张的这组图片中的第二张的放大版。。。依次类推,单击放大版的图片实现关闭效果,对于js能力不太好的我只能找度娘,然后就发现了photoswiper.js,不得不说真的好用,下面我就简单说下用法。
首先,和使用其他插件一样找到必须的资源也就是css,js等必须的文件,然后引入它们,并且引入自己在项目中肯定会用到的基础文件比如jq.和自己写的css文件比如style.css这个名字是你自己取的,可随意,最好结合项目取名。

<link rel="stylesheet" type="text/css" href="css/photoswipe.css">
<link rel="stylesheet prefetch" href="css/default-skin/default-skin.css">
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="js/jquery.min.js"></script>
<script src="js/photoswipe.js"></script>//实际应用时最好引入压缩版min.js(css同理)
<script src="js/photoswipe-ui-default.min.js"></script>

其次,在需要实现此效果的图片组外层加入下面这些结构:

<div class="my-gallery" data-pswp-uid="1">
    <div>
        <a href="images/3.png" data-size="750x980">
            <img style="height:100%;" src="images/1.png">
        </a>
    </div>
    <div>
        <a href="images/3.png" data-size="750x980">
            <img style="height:100%;" src="images/2.png">
        </a>
    </div>
    <div>
        <a href="images/3.png" data-size="750x980">
            <img style="height:100%;" src="images/3.png">
        </a>
    </div>
</div>

其实最重要的就是class=”my-gallery” data-pswp-uid=”1”和也是和photoswiper.js产生关联的钥匙其中a标签里面的data-size是设置展示的放大图的大小的,而href指向这个图,一般是原图。如果你想给展示的放大图添加附加信息,你可以在最外层div下再嵌套一层div,当然这个你可以依据设计需求自己改写页面结构在style.css中重置default-skin.css或photoswipe.css中的某些样式或者书写自己想要的样式,但是上述的关键钥匙必须存在。
然后,将下面这段代码完整的粘贴到你的页面中(这是放大版的结构设置以及一些小组件,比如分享按钮,关闭按钮等):

<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="pswp__bg"></div>
    <div class="pswp__scroll-wrap">
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>
        <div class="pswp__ui pswp__ui--hidden">
            <div class="pswp__top-bar">
                <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>
                <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>

其次,将下面核心的js代码全部粘贴过去(需要实现的小功能基本上都有,或者在api上找到相应的然后添加到参数里即可,比如实现单击放大的图片就退回原来的小图功能就是options里面的tapToClose设置为true即可,如果不需要这个功能设置为false或者直接删除这一行代码即可。):

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,
           //点击图片关闭
           tapToClose: true,
            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');


//  $(".hairImg>div").each(function(){
//      $(this).height($(this).width());
//  });
    function more(obj,id) {
        if ($('#txt'+id).is(":hidden")) {
            $('#p'+id).hide();
            $('#txt'+id).show();
            obj.innerHTML='收起';
        } else {
            $('#p'+id).show();
            $('#txt'+id).hide();
            obj.innerHTML='全文';
        }
    }

最后,展示下我的demo效果图:
仿微信朋友圈图片点击放大效果
仿微信朋友圈图片点击放大效果
好了,这就是所有的干货,希望对你们有所帮助。貌似photoswiper.js api里面有更简化的,小伙伴们也可以去读一下api。相关文件的下载地址可以去Github:点击这里