入門css
您應知道以前先作起事情:html
1. PhotoSwipe不是一個簡單的jQuery插件,至少基本的JavaScript知識才能安裝。html5
2. PhotoSwipe須要預約義的圖像尺寸(更多關於這一點)。node
3. 若是您在非迴應網站上使用PhotoSwipe - 控制將在移動進行換算(整頁縮放)。因此你須要實現自定義控件(在右上角例如單個大關閉按鈕)。git
4. 文檔中全部的代碼是純香草JS和支持IE8及以上。若是您的網站或應用程序使用了一些JavaScript框架(像jQuery或MooTools的),或者你並不須要支持舊的瀏覽器 - 隨意簡化代碼。github
5. 避免對移動服務的大圖像(大於2000x1500px),由於它們會極大地下降動畫性能,並可能致使崩潰(尤爲是iOS上的Safari瀏覽器)。可能的解決方案:一個單獨的網頁上投放響應圖像,或者打開的圖像,或者(在常見問題解答更多)使用支持平鋪圖像(如傳單)庫。ajax
初始化數組
第1步:包括JS和CSS文件瀏覽器
您能夠在GitHub的信息庫DIST/文件夾中找到它們。薩斯和未編譯的JS文件夾中的src /。我建議使用無禮的話,若是你打算修改現有的樣式,有代碼的結構和評述。https://github.com/dimsemenov/PhotoSwipeapp
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]-->