PhotoSwipe中文API(一)

入门

您应知道之前先做起事情:

1. PhotoSwipe不是一个简单的jQuery插件,至少基本的JavaScript知识才能安装。

2. PhotoSwipe需要预定义的图像尺寸(更多关于这一点)。

3. 如果您在非回应网站上使用PhotoSwipe - 控制将在移动进行换算(整页缩放)。所以你需要实现自定义控件(在右上角例如单个大关闭按钮)。

4. 文档中所有的代码是纯香草JS和支持IE8及以上。如果您的网站或应用程序使用了一些JavaScript框架(像jQuery或MooTools的),或者你并不需要支持旧的浏览器 - 随意简化代码。

5. 避免对移动服务的大图像(大于2000x1500px),因为它们会极大地降低动画性能,并可能导致崩溃(尤其是iOS上的Safari浏览器)。可能的解决方案:一个单独的网页上投放响应图像,或者打开的图像,或者(在常见问题解答更多)使用支持平铺图像(如传单)库。

初始化

第1步:包括JS和CSS文件

您可以在GitHub的信息库DIST/文件夹中找到它们。萨斯和未编译的JS文件夹中的src /。我建议使用无礼的话,如果你打算修改现有的样式,有代码的结构和评述。https://github.com/dimsemenov/PhotoSwipe

 1 <!-- Core CSS file -->
 2 <link rel="stylesheet" href="path/to/photoswipe.css"> 
 3 
 4 <!-- Skin CSS file (styling of UI - buttons, caption, etc.)
 5      In the folder of skin CSS file there are also:
 6      - .png and .svg icons sprite, 
 7      - preloader.gif (for browsers that do not support CSS animations) -->
 8 <link rel="stylesheet" href="path/to/default-skin/default-skin.css"> 
 9 
10 <!-- Core JS file -->
11 <script src="path/to/photoswipe.min.js"></script> 
12 
13 <!-- UI JS file -->
14 <script src="path/to/photoswipe-ui-default.min.js"></script> 

不要紧,如何以及在哪里将包括JS和CSS文件。只有当你调用新PhotoSwipe代码被执行()。可以随意推迟文件加载,如果你不需要PhotoSwipe被初步打开。

PhotoSwipe还支持AMD装载机(如RequireJS)和CommonJS的,使用起来就像这样:

 1 require([ 
 2         'path/to/photoswipe.js', 
 3         'path/to/photoswipe-ui-default.js' 
 4     ], function( PhotoSwipe, PhotoSwipeUI_Default ) {
 5 
 6     //      var gallery = new PhotoSwipe( someElement, PhotoSwipeUI_Default ...
 7     //      gallery.init() 
 8     //      ...
 9 
10 });

而且,您可以通过鲍尔安装(安装鲍尔photoswipe),或NPM(NPM安装photoswipe)。

第2步:PhotoSwipe(.pswp)元素添加到DOM

您可以通过JS动态添加HTML代码(直接在初始化之前),或者有它的页面开始(喜欢它的演示页面上完成)。该代码可以在任何地方附加,但理想的结束</ body>之前。 (你用相同的UI类只要)你可以重复使用它在多个画廊。

 1 <!-- Root element of PhotoSwipe. Must have class pswp. -->
 2 <div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">
 3 
 4     <!-- Background of PhotoSwipe. 
 5          It's a separate element as animating opacity is faster than rgba(). -->
 6     <div class="pswp__bg"></div>
 7 
 8     <!-- Slides wrapper with overflow:hidden. -->
 9     <div class="pswp__scroll-wrap">
10 
11         <!-- Container that holds slides. 
12             PhotoSwipe keeps only 3 of them in the DOM to save memory.
13             Don't modify these 3 pswp__item elements, data is added later on. -->
14         <div class="pswp__container">
15             <div class="pswp__item"></div>
16             <div class="pswp__item"></div>
17             <div class="pswp__item"></div>
18         </div>
19 
20         <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
21         <div class="pswp__ui pswp__ui--hidden">
22 
23             <div class="pswp__top-bar">
24 
25                 <!--  Controls are self-explanatory. Order can be changed. -->
26 
27                 <div class="pswp__counter"></div>
28 
29                 <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
30 
31                 <button class="pswp__button pswp__button--share" title="Share"></button>
32 
33                 <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
34 
35                 <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>
36 
37                 <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
38                 <!-- element will get class pswp__preloader--active when preloader is running -->
39                 <div class="pswp__preloader">
40                     <div class="pswp__preloader__icn">
41                       <div class="pswp__preloader__cut">
42                         <div class="pswp__preloader__donut"></div>
43                       </div>
44                     </div>
45                 </div>
46             </div>
47 
48             <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
49                 <div class="pswp__share-tooltip"></div> 
50             </div>
51 
52             <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
53             </button>
54 
55             <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
56             </button>
57 
58             <div class="pswp__caption">
59                 <div class="pswp__caption__center"></div>
60             </div>
61 
62         </div>
63 
64     </div>
65 
66 </div>

pswp__bg,pswp__scroll换行,pswp__container和pswp__item元素的顺序不应改变。

你可能会问,为什么PhotoSwipe不通过JS自动添加该代码,原因很简单 - 只是为了节省文件大小的情况下,如果你需要的布局做一些修改。

步骤3:初始化

执行PhotoSwipe构造函数。它接受4个参数:

1. 从步骤2(它必须被添加到DOM).pswp元件。

2. PhotoSwipe UI类。如果包括了默认photoswipe-UI-default.js,类将是PhotoSwipeUI_Default。可以是假的。

3. 与对象(幻灯片)阵列。

4. options

 1 var pswpElement = document.querySelectorAll('.pswp')[0];
 2 
 3 // build items array
 4 var items = [
 5     {
 6         src: 'https://placekitten.com/600/400',
 7         w: 600,
 8         h: 400
 9     },
10     {
11         src: 'https://placekitten.com/1200/900',
12         w: 1200,
13         h: 900
14     }
15 ];
16 
17 // define options (if needed)
18 var options = {
19     // optionName: 'option value'
20     // for example:
21     index: 0 // start at first slide
22 };
23 
24 // Initializes and opens PhotoSwipe
25 var gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);
26 gallery.init();

在最后你应该得到的东西是这样的:

html:

 1 <button id="btn">Open PhotoSwipe</button>
 2 
 3 <!-- Root element of PhotoSwipe. Must have class pswp. -->
 4 <div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">
 5 
 6     <!-- Background of PhotoSwipe. 
 7          It's a separate element, as animating opacity is faster than rgba(). -->
 8     <div class="pswp__bg"></div>
 9 
10     <!-- Slides wrapper with overflow:hidden. -->
11     <div class="pswp__scroll-wrap">
12 
13         <!-- Container that holds slides. PhotoSwipe keeps only 3 slides in DOM to save memory. -->
14         <div class="pswp__container">
15             <!-- don't modify these 3 pswp__item elements, data is added later on -->
16             <div class="pswp__item"></div>
17             <div class="pswp__item"></div>
18             <div class="pswp__item"></div>
19         </div>
20 
21         <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
22         <div class="pswp__ui pswp__ui--hidden">
23 
24             <div class="pswp__top-bar">
25 
26                 <!--  Controls are self-explanatory. Order can be changed. -->
27 
28                 <div class="pswp__counter"></div>
29 
30                 <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
31 
32                 <button class="pswp__button pswp__button--share" title="Share"></button>
33 
34                 <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
35 
36                 <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>
37 
38                 <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
39                 <!-- element will get class pswp__preloader--active when preloader is running -->
40                 <div class="pswp__preloader">
41                     <div class="pswp__preloader__icn">
42                       <div class="pswp__preloader__cut">
43                         <div class="pswp__preloader__donut"></div>
44                       </div>
45                     </div>
46                 </div>
47             </div>
48 
49             <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
50                 <div class="pswp__share-tooltip"></div> 
51             </div>
52 
53             <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
54             </button>
55 
56             <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
57             </button>
58 
59             <div class="pswp__caption">
60                 <div class="pswp__caption__center"></div>
61             </div>
62 
63           </div>
64 
65         </div>
66 
67 </div>

js : 

var openPhotoSwipe = function() {
    var pswpElement = document.querySelectorAll('.pswp')[0];

    // build items array
    var items = [
        {
            src: 'https://farm2.staticflickr.com/1043/5186867718_06b2e9e551_b.jpg',
            w: 964,
            h: 1024
        },
        {
            src: 'https://farm7.staticflickr.com/6175/6176698785_7dee72237e_b.jpg',
            w: 1024,
            h: 683
        }
    ];
    
    // define options (if needed)
    var options = {
             // history & focus options are disabled on CodePen        
        history: false,
        focus: false,

        showAnimationDuration: 0,
        hideAnimationDuration: 0
        
    };
    
    var gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);
    gallery.init();
};

openPhotoSwipe();

document.getElementById('btn').onclick = openPhotoSwipe;

结果:

创建幻灯片对象的数组

数组应包含有关幻灯片数据中的每个对象,也可以是你希望在PhotoSwipe显示任何东西 - 路径图像,标题字符串,股数,评论等。

默认情况下PhotoSwipe只使用了5个属性:SRC(路径图),W(图像宽度),H(图像高度),MSRC(路径的小图像占位符,大的图像会在上面装),HTML(自定义HTML,更 关于它)。

在导航,PhotoSwipe增加自己的属性到这个对象(如MINZOOM或加载)。

 1 var slides = [
 2 
 3     // slide 1
 4     {
 5 
 6         src: 'path/to/image1.jpg', // path to image
 7         w: 1024, // image width
 8         h: 768, // image height
 9 
10         msrc: 'path/to/small-image.jpg', // small image placeholder,
11                         // main (large) image loads on top of it,
12                         // if you skip this parameter - grey rectangle will be displayed,
13                         // try to define this property only when small image was loaded before
14 
15 
16 
17         title: 'Image Caption'  // used by Default PhotoSwipe UI
18                                 // if you skip it, there won't be any caption
19 
20 
21         // You may add more properties here and use them.
22         // For example, demo gallery uses "author" property, which is used in the caption.
23         // author: 'John Doe'
24 
25     },
26 
27     // slide 2
28     {
29         src: 'path/to/image2.jpg', 
30         w: 600, 
31         h: 600
32 
33         // etc.
34     }
35 
36     // etc.
37 
38 ];

您可以动态地定义幻灯片对象的属性PhotoSwipe读取它们直接之前,使用gettingData事件(在文档的API部分的更多信息)。例如,该技术可用于为不同的屏幕尺寸不同的图像。

如何从一个链接列表建立幻灯片的数组

让我们假设你有一个看起来像这样(约画廊的标记更多信息)的链接/缩略图列表:

 1 <div class="my-gallery" itemscope itemtype="http://schema.org/ImageGallery">
 2 
 3     <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
 4         <a href="large-image.jpg" itemprop="contentUrl" data-size="600x400">
 5             <img src="small-image.jpg" itemprop="thumbnail" alt="Image description" />
 6         </a>
 7         <figcaption itemprop="caption description">Image caption</figcaption>
 8     </figure>
 9 
10     <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
11         <a href="large-image.jpg" itemprop="contentUrl" data-size="600x400">
12             <img src="small-image.jpg" itemprop="thumbnail" alt="Image description" />
13         </a>
14         <figcaption itemprop="caption description">Image caption</figcaption>
15     </figure>
16 
17 
18 </div>

...你要点击缩略图与大型图像打开PhotoSwipe(喜欢它的演示页上完成)。所有你需要做的是:

1. 绑定click事件链接/缩略图。

2. 用户点击缩略图后,找到它的索引。

3. 创建DOM元素幻灯片对象的数组 - 通过各环节循环和检索href属性(大图像URL),数据大小属性(其大小),缩略图的SRC和字幕的内容。

PhotoSwipe并不真正关心你将如何做到这一点。如果你使用像jQuery或MooTools的框架,或者如果你不需要支持IE8,代码可以大大简化。

这里是纯香草JS实现与IE8的支持:

  1 var initPhotoSwipeFromDOM = function(gallerySelector) {
  2 
  3     // parse slide data (url, title, size ...) from DOM elements 
  4     // (children of gallerySelector)
  5     var parseThumbnailElements = function(el) {
  6         var thumbElements = el.childNodes,
  7             numNodes = thumbElements.length,
  8             items = [],
  9             figureEl,
 10             linkEl,
 11             size,
 12             item;
 13 
 14         for(var i = 0; i < numNodes; i++) {
 15 
 16             figureEl = thumbElements[i]; // <figure> element
 17 
 18             // include only element nodes 
 19             if(figureEl.nodeType !== 1) {
 20                 continue;
 21             }
 22 
 23             linkEl = figureEl.children[0]; // <a> element
 24 
 25             size = linkEl.getAttribute('data-size').split('x');
 26 
 27             // create slide object
 28             item = {
 29                 src: linkEl.getAttribute('href'),
 30                 w: parseInt(size[0], 10),
 31                 h: parseInt(size[1], 10)
 32             };
 33 
 34 
 35 
 36             if(figureEl.children.length > 1) {
 37                 // <figcaption> content
 38                 item.title = figureEl.children[1].innerHTML; 
 39             }
 40 
 41             if(linkEl.children.length > 0) {
 42                 // <img> thumbnail element, retrieving thumbnail url
 43                 item.msrc = linkEl.children[0].getAttribute('src');
 44             } 
 45 
 46             item.el = figureEl; // save link to element for getThumbBoundsFn
 47             items.push(item);
 48         }
 49 
 50         return items;
 51     };
 52 
 53     // find nearest parent element
 54     var closest = function closest(el, fn) {
 55         return el && ( fn(el) ? el : closest(el.parentNode, fn) );
 56     };
 57 
 58     // triggers when user clicks on thumbnail
 59     var onThumbnailsClick = function(e) {
 60         e = e || window.event;
 61         e.preventDefault ? e.preventDefault() : e.returnValue = false;
 62 
 63         var eTarget = e.target || e.srcElement;
 64 
 65         // find root element of slide
 66         var clickedListItem = closest(eTarget, function(el) {
 67             return (el.tagName && el.tagName.toUpperCase() === 'FIGURE');
 68         });
 69 
 70         if(!clickedListItem) {
 71             return;
 72         }
 73 
 74         // find index of clicked item by looping through all child nodes
 75         // alternatively, you may define index via data- attribute
 76         var clickedGallery = clickedListItem.parentNode,
 77             childNodes = clickedListItem.parentNode.childNodes,
 78             numChildNodes = childNodes.length,
 79             nodeIndex = 0,
 80             index;
 81 
 82         for (var i = 0; i < numChildNodes; i++) {
 83             if(childNodes[i].nodeType !== 1) { 
 84                 continue; 
 85             }
 86 
 87             if(childNodes[i] === clickedListItem) {
 88                 index = nodeIndex;
 89                 break;
 90             }
 91             nodeIndex++;
 92         }
 93 
 94 
 95 
 96         if(index >= 0) {
 97             // open PhotoSwipe if valid index found
 98             openPhotoSwipe( index, clickedGallery );
 99         }
100         return false;
101     };
102 
103     // parse picture index and gallery index from URL (#&pid=1&gid=2)
104     var photoswipeParseHash = function() {
105         var hash = window.location.hash.substring(1),
106         params = {};
107 
108         if(hash.length < 5) {
109             return params;
110         }
111 
112         var vars = hash.split('&');
113         for (var i = 0; i < vars.length; i++) {
114             if(!vars[i]) {
115                 continue;
116             }
117             var pair = vars[i].split('=');  
118             if(pair.length < 2) {
119                 continue;
120             }           
121             params[pair[0]] = pair[1];
122         }
123 
124         if(params.gid) {
125             params.gid = parseInt(params.gid, 10);
126         }
127 
128         return params;
129     };
130 
131     var openPhotoSwipe = function(index, galleryElement, disableAnimation, fromURL) {
132         var pswpElement = document.querySelectorAll('.pswp')[0],
133             gallery,
134             options,
135             items;
136 
137         items = parseThumbnailElements(galleryElement);
138 
139         // define options (if needed)
140         options = {
141 
142             // define gallery index (for URL)
143             galleryUID: galleryElement.getAttribute('data-pswp-uid'),
144 
145             getThumbBoundsFn: function(index) {
146                 // See Options -> getThumbBoundsFn section of documentation for more info
147                 var thumbnail = items[index].el.getElementsByTagName('img')[0], // find thumbnail
148                     pageYScroll = window.pageYOffset || document.documentElement.scrollTop,
149                     rect = thumbnail.getBoundingClientRect(); 
150 
151                 return {x:rect.left, y:rect.top + pageYScroll, w:rect.width};
152             }
153 
154         };
155 
156         // PhotoSwipe opened from URL
157         if(fromURL) {
158             if(options.galleryPIDs) {
159                 // parse real index when custom PIDs are used 
160                 // http://photoswipe.com/documentation/faq.html#custom-pid-in-url
161                 for(var j = 0; j < items.length; j++) {
162                     if(items[j].pid == index) {
163                         options.index = j;
164                         break;
165                     }
166                 }
167             } else {
168                 // in URL indexes start from 1
169                 options.index = parseInt(index, 10) - 1;
170             }
171         } else {
172             options.index = parseInt(index, 10);
173         }
174 
175         // exit if index not found
176         if( isNaN(options.index) ) {
177             return;
178         }
179 
180         if(disableAnimation) {
181             options.showAnimationDuration = 0;
182         }
183 
184         // Pass data to PhotoSwipe and initialize it
185         gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);
186         gallery.init();
187     };
188 
189     // loop through all gallery elements and bind events
190     var galleryElements = document.querySelectorAll( gallerySelector );
191 
192     for(var i = 0, l = galleryElements.length; i < l; i++) {
193         galleryElements[i].setAttribute('data-pswp-uid', i+1);
194         galleryElements[i].onclick = onThumbnailsClick;
195     }
196 
197     // Parse URL and open gallery if it contains #&pid=3&gid=1
198     var hashData = photoswipeParseHash();
199     if(hashData.pid && hashData.gid) {
200         openPhotoSwipe( hashData.pid ,  galleryElements[ hashData.gid - 1 ], true, true );
201     }
202 };
203 
204 // execute above function
205 initPhotoSwipeFromDOM('.my-gallery');

例如在CodePen(重点和历史选项被禁用,由于嵌入的问题):

  1 <h2>First gallery:</h2>
  2 
  3   <div class="my-gallery" itemscope itemtype="http://schema.org/ImageGallery">
  4 
  5     <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
  6       <a href="https://farm3.staticflickr.com/2567/5697107145_a4c2eaa0cd_o.jpg" itemprop="contentUrl" data-size="1024x1024">
  7           <img src="https://farm3.staticflickr.com/2567/5697107145_3c27ff3cd1_m.jpg" itemprop="thumbnail" alt="Image description" />
  8       </a>
  9                                           <figcaption itemprop="caption description">Image caption  1</figcaption>
 10                                           
 11     </figure>
 12 
 13     <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
 14       <a href="https://farm2.staticflickr.com/1043/5186867718_06b2e9e551_b.jpg" itemprop="contentUrl" data-size="964x1024">
 15           <img src="https://farm2.staticflickr.com/1043/5186867718_06b2e9e551_m.jpg" itemprop="thumbnail" alt="Image description" />
 16       </a>
 17       <figcaption itemprop="caption description">Image caption 2</figcaption>
 18     </figure>
 19 
 20     <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
 21       <a href="https://farm7.staticflickr.com/6175/6176698785_7dee72237e_b.jpg" itemprop="contentUrl" data-size="1024x683">
 22           <img src="https://farm7.staticflickr.com/6175/6176698785_7dee72237e_m.jpg" itemprop="thumbnail" alt="Image description" />
 23       </a>
 24       <figcaption itemprop="caption description">Image caption 3</figcaption>
 25     </figure>
 26 
 27     <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
 28       <a href="https://farm6.staticflickr.com/5023/5578283926_822e5e5791_b.jpg" itemprop="contentUrl" data-size="1024x768">
 29           <img src="https://farm6.staticflickr.com/5023/5578283926_822e5e5791_m.jpg" itemprop="thumbnail" alt="Image description" />
 30       </a>
 31       <figcaption itemprop="caption description">Image caption 4</figcaption>
 32     </figure>
 33 
 34 
 35   </div>
 36 
 37 <h2>Second gallery:</h2>
 38 
 39   <div class="my-gallery" itemscope itemtype="http://schema.org/ImageGallery">
 40 
 41   
 42 
 43     <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
 44       <a href="https://farm2.staticflickr.com/1043/5186867718_06b2e9e551_b.jpg" itemprop="contentUrl" data-size="964x1024">
 45           <img src="https://farm2.staticflickr.com/1043/5186867718_06b2e9e551_m.jpg" itemprop="thumbnail" alt="Image description" />
 46       </a>
 47       <figcaption itemprop="caption description">Image caption 2.1</figcaption>
 48     </figure>
 49 
 50     <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
 51       <a href="https://farm7.staticflickr.com/6175/6176698785_7dee72237e_b.jpg" itemprop="contentUrl" data-size="1024x683">
 52           <img src="https://farm7.staticflickr.com/6175/6176698785_7dee72237e_m.jpg" itemprop="thumbnail" alt="Image description" />
 53       </a>
 54       <figcaption itemprop="caption description">Image caption 2.2</figcaption>
 55     </figure>
 56 
 57     <figure itemprop="associatedMedia" itemscope itemtype="http://schema.org/ImageObject">
 58       <a href="https://farm6.staticflickr.com/5023/5578283926_822e5e5791_b.jpg" itemprop="contentUrl" data-size="1024x768">
 59           <img src="https://farm6.staticflickr.com/5023/5578283926_822e5e5791_m.jpg" itemprop="thumbnail" alt="Image description" />
 60       </a>
 61       <figcaption itemprop="caption description">Image caption 2.3</figcaption>
 62     </figure>
 63 
 64 
 65   </div>
 66 
 67 
 68 
 69 <!-- Root element of PhotoSwipe. Must have class pswp. -->
 70 <div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">
 71 
 72     <!-- Background of PhotoSwipe. 
 73          It's a separate element, as animating opacity is faster than rgba(). -->
 74     <div class="pswp__bg"></div>
 75 
 76     <!-- Slides wrapper with overflow:hidden. -->
 77     <div class="pswp__scroll-wrap">
 78 
 79         <!-- Container that holds slides. PhotoSwipe keeps only 3 slides in DOM to save memory. -->
 80         <!-- don't modify these 3 pswp__item elements, data is added later on. -->
 81         <div class="pswp__container">
 82             <div class="pswp__item"></div>
 83             <div class="pswp__item"></div>
 84             <div class="pswp__item"></div>
 85         </div>
 86 
 87         <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
 88         <div class="pswp__ui pswp__ui--hidden">
 89 
 90             <div class="pswp__top-bar">
 91 
 92                 <!--  Controls are self-explanatory. Order can be changed. -->
 93 
 94                 <div class="pswp__counter"></div>
 95 
 96                 <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>
 97 
 98                 <button class="pswp__button pswp__button--share" title="Share"></button>
 99 
100                 <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>
101 
102                 <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>
103 
104                 <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
105                 <!-- element will get class pswp__preloader--active when preloader is running -->
106                 <div class="pswp__preloader">
107                     <div class="pswp__preloader__icn">
108                       <div class="pswp__preloader__cut">
109                         <div class="pswp__preloader__donut"></div>
110                       </div>
111                     </div>
112                 </div>
113             </div>
114 
115             <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
116                 <div class="pswp__share-tooltip"></div> 
117             </div>
118 
119             <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
120             </button>
121 
122             <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
123             </button>
124 
125             <div class="pswp__caption">
126                 <div class="pswp__caption__center"></div>
127             </div>
128 
129           </div>
130 
131         </div>
132 
133 </div>
 1 .my-gallery {
 2   width: 100%;
 3   float: left;
 4 }
 5 .my-gallery img {
 6   width: 100%;
 7   height: auto;
 8 }
 9 .my-gallery figure {
10   display: block;
11   float: left;
12   margin: 0 5px 5px 0;
13   width: 150px;
14 }
15 .my-gallery figcaption {
16   display: none;
17 }
  1 var initPhotoSwipeFromDOM = function(gallerySelector) {
  2 
  3     // parse slide data (url, title, size ...) from DOM elements 
  4     // (children of gallerySelector)
  5     var parseThumbnailElements = function(el) {
  6         var thumbElements = el.childNodes,
  7             numNodes = thumbElements.length,
  8             items = [],
  9             figureEl,
 10             linkEl,
 11             size,
 12             item;
 13 
 14         for(var i = 0; i < numNodes; i++) {
 15 
 16             figureEl = thumbElements[i]; // <figure> element
 17 
 18             // include only element nodes 
 19             if(figureEl.nodeType !== 1) {
 20                 continue;
 21             }
 22 
 23             linkEl = figureEl.children[0]; // <a> element
 24 
 25             size = linkEl.getAttribute('data-size').split('x');
 26 
 27             // create slide object
 28             item = {
 29                 src: linkEl.getAttribute('href'),
 30                 w: parseInt(size[0], 10),
 31                 h: parseInt(size[1], 10)
 32             };
 33 
 34 
 35 
 36             if(figureEl.children.length > 1) {
 37                 // <figcaption> content
 38                 item.title = figureEl.children[1].innerHTML; 
 39             }
 40 
 41             if(linkEl.children.length > 0) {
 42                 // <img> thumbnail element, retrieving thumbnail url
 43                 item.msrc = linkEl.children[0].getAttribute('src');
 44             } 
 45 
 46             item.el = figureEl; // save link to element for getThumbBoundsFn
 47             items.push(item);
 48         }
 49 
 50         return items;
 51     };
 52 
 53     // find nearest parent element
 54     var closest = function closest(el, fn) {
 55         return el && ( fn(el) ? el : closest(el.parentNode, fn) );
 56     };
 57 
 58     // triggers when user clicks on thumbnail
 59     var onThumbnailsClick = function(e) {
 60         e = e || window.event;
 61         e.preventDefault ? e.preventDefault() : e.returnValue = false;
 62 
 63         var eTarget = e.target || e.srcElement;
 64 
 65         // find root element of slide
 66         var clickedListItem = closest(eTarget, function(el) {
 67             return (el.tagName && el.tagName.toUpperCase() === 'FIGURE');
 68         });
 69 
 70         if(!clickedListItem) {
 71             return;
 72         }
 73 
 74         // find index of clicked item by looping through all child nodes
 75         // alternatively, you may define index via data- attribute
 76         var clickedGallery = clickedListItem.parentNode,
 77             childNodes = clickedListItem.parentNode.childNodes,
 78             numChildNodes = childNodes.length,
 79             nodeIndex = 0,
 80             index;
 81 
 82         for (var i = 0; i < numChildNodes; i++) {
 83             if(childNodes[i].nodeType !== 1) { 
 84                 continue; 
 85             }
 86 
 87             if(childNodes[i] === clickedListItem) {
 88                 index = nodeIndex;
 89                 break;
 90             }
 91             nodeIndex++;
 92         }
 93 
 94 
 95 
 96         if(index >= 0) {
 97             // open PhotoSwipe if valid index found
 98             openPhotoSwipe( index, clickedGallery );
 99         }
100         return false;
101     };
102 
103     // parse picture index and gallery index from URL (#&pid=1&gid=2)
104     var photoswipeParseHash = function() {
105         var hash = window.location.hash.substring(1),
106         params = {};
107 
108         if(hash.length < 5) {
109             return params;
110         }
111 
112         var vars = hash.split('&');
113         for (var i = 0; i < vars.length; i++) {
114             if(!vars[i]) {
115                 continue;
116             }
117             var pair = vars[i].split('=');  
118             if(pair.length < 2) {
119                 continue;
120             }           
121             params[pair[0]] = pair[1];
122         }
123 
124         if(params.gid) {
125             params.gid = parseInt(params.gid, 10);
126         }
127 
128         return params;
129     };
130 
131     var openPhotoSwipe = function(index, galleryElement, disableAnimation, fromURL) {
132         var pswpElement = document.querySelectorAll('.pswp')[0],
133             gallery,
134             options,
135             items;
136 
137         items = parseThumbnailElements(galleryElement);
138 
139         // define options (if needed)
140         options = {
141 
142             // define gallery index (for URL)
143             galleryUID: galleryElement.getAttribute('data-pswp-uid'),
144 
145             getThumbBoundsFn: function(index) {
146                 // See Options -> getThumbBoundsFn section of documentation for more info
147                 var thumbnail = items[index].el.getElementsByTagName('img')[0], // find thumbnail
148                     pageYScroll = window.pageYOffset || document.documentElement.scrollTop,
149                     rect = thumbnail.getBoundingClientRect(); 
150 
151                 return {x:rect.left, y:rect.top + pageYScroll, w:rect.width};
152             }
153 
154         };
155 
156         // PhotoSwipe opened from URL
157         if(fromURL) {
158             if(options.galleryPIDs) {
159                 // parse real index when custom PIDs are used 
160                 // http://photoswipe.com/documentation/faq.html#custom-pid-in-url
161                 for(var j = 0; j < items.length; j++) {
162                     if(items[j].pid == index) {
163                         options.index = j;
164                         break;
165                     }
166                 }
167             } else {
168                 // in URL indexes start from 1
169                 options.index = parseInt(index, 10) - 1;
170             }
171         } else {
172             options.index = parseInt(index, 10);
173         }
174 
175         // exit if index not found
176         if( isNaN(options.index) ) {
177             return;
178         }
179 
180         if(disableAnimation) {
181             options.showAnimationDuration = 0;
182         }
183 
184         // Pass data to PhotoSwipe and initialize it
185         gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);
186         gallery.init();
187     };
188 
189     // loop through all gallery elements and bind events
190     var galleryElements = document.querySelectorAll( gallerySelector );
191 
192     for(var i = 0, l = galleryElements.length; i < l; i++) {
193         galleryElements[i].setAttribute('data-pswp-uid', i+1);
194         galleryElements[i].onclick = onThumbnailsClick;
195     }
196 
197     // Parse URL and open gallery if it contains #&pid=3&gid=1
198     var hashData = photoswipeParseHash();
199     if(hashData.pid && hashData.gid) {
200         openPhotoSwipe( hashData.pid ,  galleryElements[ hashData.gid - 1 ], true, true );
201     }
202 };
203 
204 // execute above function
205 initPhotoSwipeFromDOM('.my-gallery');

提示:您可以从CodePen例如下载在本地发挥它(编辑上CodePen - >分享 - >导出.zip文件)。

如果您使用的标记,从这个例子不同,你需要编辑功能解析缩略图元素。

如果你没有在纯JavaScript经验,不知道如何解析DOM,请参阅怪异模式和文档在MSDN上。

需要注意的是IE8不支持HTML5<图>和<figcaption>元素,所以你需要在<head>部分(托管版本的例子中使用cdnjs)html5shiv:

<!--[if lt IE 9]>
    <script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.2/html5shiv.min.js"></script>
<![endif]-->

 

posted @ 2016-07-22 17:10  jiangxiaobo  阅读(48033)  评论(1编辑  收藏  举报