--- layout: default title: "PhotoSwipe Documentation: Getting Started" h1_title: Getting Started description: PhotoSwipe image gallery getting started guide. addjs: true canonical_url: http://photoswipe.com/documentation/getting-started.html buildtool: true markdownpage: true --- 开始之前应该知道的第一件事: - PhotoSwipe 不是一个简单的 jQuery 插件,至少需要基本的 JavaScript 知识才能安装。 - PhotoSwipe 需要预定义的图像尺寸([more about this](faq.html#image-size))。 - 如果你在无响应的网站上使用 PhotoSwipe –控件将在移动设备上进行缩放(当整个页面被缩放时)。因此,你将需要实现自定义控件(例如,在右上角的单个大型关闭按钮)。 - 文档中的所有代码都是纯 VanillaJS,并支持 IE8 及以上版本。如果你的网站或应用程序使用了一些 JavaScript framework (比如 jQuery 或 MooTools),或者你不需要支持旧的浏览器——请随意简化代码。 - 避免为移动设备提供大图片(大于 2000x1500px),因为它们会大大降低动画性能,并可能导致崩溃(尤其是在 iOS Safari 上)。可能的解决方案:[提供响应图像](responsive-images.html),或在单独的页面上打开图像,或使用支持图像平铺的库(例如 [Leaflet](http://leafletjs.com/))([more in FAQ](faq.html#mobile-crash))。 ## 初始化 ### 第一步:包含 JS 和 CSS 文件 你可以在 [dist/](https://github.com/dimsemenov/PhotoSwipe/tree/master/dist) 的 [GitHub](https://github.com/dimsemenov/PhotoSwipe)库文件夹中找到它们。Sass 和未编译的 JS 文件在 [src/](https://github.com/dimsemenov/PhotoSwipe/tree/master/src) 文件夹中。如果你计划修改现有的样式,我建议你使用 Sass,因为那里的代码是结构化和注释的。 ```html ``` 不管你将如何以及在哪里包含 JS 和 CSS 文件。只有在调用 `new PhotoSwipe()` 时,才执行代码。所以,如果你不需要 PhotoSwipe 一开始就打开文件,可以随时推迟加载。 PhotoSwipe 还支持 AMD 加载程序(如 RequireJS)和 CommonJS,可以这样使用它们: ```javascript require([ 'path/to/photoswipe.js', 'path/to/photoswipe-ui-default.js' ], function( PhotoSwipe, PhotoSwipeUI_Default ) { // var gallery = new PhotoSwipe( someElement, PhotoSwipeUI_Default ... // gallery.init() // ... }); ``` 此外,你还可以通过 bower(“bower install PhotoSwipe ”)或 [NPM](https://www.npmjs.com/package/photoswipe)(“npm install PhotoSwipe ”)安装它。 ### 步骤 2:添加 PhotoSwipe (。pswp)元素到 DOM 你可以通过 JS 动态地添加 HTML 代码(直接在初始化之前),或者最初将其放在页面中(就像在演示页面中所做的那样)。这段代码可以附加到任何地方,但理想的情况是在结束 `` 之前。你可以跨多个图库重用它(只要你使用相同的 UI 类)。 ```html ``` 不应更改 `pswp__bg`、`pswp__scroll-wrap`、`pswp__container` 和 `pswp__item` 元素的顺序。 你可能会问,为什么 PhotoSwipe 不通过 JS 自动添加此代码,原因很简单 –只是为了节省文件大小,以防你需要对布局进行一些修改。 ### 步骤 3:初始化 执行 `PhotoSwipe` 构造函数。它接受 4 个论点: 1. 步骤 2 中的 `.pswp` 元素(必须将其添加到 DOM 中)。 2. PhotoSwipe UI 类。如果包含默认的 `photoswipe-ui-default.js`,则类将是 `PhotoSwipeUI_Default`。可以 `false`。 3. 带有对象(幻灯片)的数组。 4. [Options](options.html). ```javascript var pswpElement = document.querySelectorAll('.pswp')[0]; // build items array var items = [ { src: 'https://placekitten.com/600/400', w: 600, h: 400 }, { src: 'https://placekitten.com/1200/900', w: 1200, h: 900 } ]; // define options (if needed) var options = { // optionName: 'option value' // for example: index: 0 // start at first slide }; // Initializes and opens PhotoSwipe var gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options); gallery.init(); ``` 最后,你应该得到这样的结论:

View example on CodePen →

## 创建幻灯片对象数组 数组中的每个对象都应该包含有关幻灯片的数据,它可以是你希望在 PhotoSwipe 中显示的任何内容-图像路径、标题字符串、共享数量、注释等。 默认情况下 PhotoSwipe 只使用 5 个属性:`src`(图像路径),`w`(图像宽度),`h`(图像高度),`msrc`(小图像占位符路径,大图像将被加载在顶部),`html`(自定义 HTML,[more about it](custom-html-in-slides.html))。 在导航过程中, PhotoSwipe 将其自身的属性添加到此对象(例如 `minZoom` 或 `loaded`)。 ```javascript var slides = [ // slide 1 { src: 'path/to/image1.jpg', // path to image w: 1024, // image width h: 768, // image height msrc: 'path/to/small-image.jpg', // small image placeholder, // main (large) image loads on top of it, // if you skip this parameter - grey rectangle will be displayed, // try to define this property only when small image was loaded before title: 'Image Caption' // used by Default PhotoSwipe UI // if you skip it, there won't be any caption // You may add more properties here and use them. // For example, demo gallery uses "author" property, which is used in the caption. // author: 'John Doe' }, // slide 2 { src: 'path/to/image2.jpg', w: 600, h: 600 // etc. } // etc. ]; ``` 你可以在 PhotoSwipe 读取幻灯片对象属性之前直接动态地定义它们,使用 `gettingData` 事件(更多信息在 [API section of docs](api.html) 中)。例如,这种技术可以用来 [服务不同的形象](responsive-images.html) 用于不同的屏幕尺寸。 ## 如何从链接列表中构建幻灯片数组 假设你有一个看起来像这样的链接 / 缩略图列表([更多关于图库标记的信息](seo.html)): ```html ``` ...你想要点击缩略图来打开大图片的 PhotoSwipe (就像在演示页面上做的那样)。你需要做的就是: 1. 将单击事件绑定到链接 / 缩略图。 2. 用户点击缩略图后,找到它的索引。 3. 从 DOM 元素创建一个幻灯片对象数组——循环所有链接并检索 `href` 属性(大图像 URL)、`data-size` 属性(其大小)、`src` 缩略图和标题内容。 PhotoSwipe 其实并不在乎你将如何做到这一点。如果你使用像 jQuery 或 MooTools 这样的框架,或者如果你不需要支持 IE8,那么代码可以大大简化。 下面是支持 IE8 的纯 Vanilla JS 实现: ```javascript var initPhotoSwipeFromDOM = function(gallerySelector) { // parse slide data (url, title, size ...) from DOM elements // (children of gallerySelector) var parseThumbnailElements = function(el) { var thumbElements = el.childNodes, numNodes = thumbElements.length, items = [], figureEl, linkEl, size, item; for(var i = 0; i < numNodes; i++) { figureEl = thumbElements[i]; //
element // include only element nodes if(figureEl.nodeType !== 1) { continue; } linkEl = figureEl.children[0]; // element size = linkEl.getAttribute('data-size').split('x'); // create slide object item = { src: linkEl.getAttribute('href'), w: parseInt(size[0], 10), h: parseInt(size[1], 10) }; if(figureEl.children.length > 1) { //
content item.title = figureEl.children[1].innerHTML; } if(linkEl.children.length > 0) { // thumbnail element, retrieving thumbnail url item.msrc = linkEl.children[0].getAttribute('src'); } item.el = figureEl; // save link to element for getThumbBoundsFn items.push(item); } return items; }; // find nearest parent element var closest = function closest(el, fn) { return el && ( fn(el) ? el : closest(el.parentNode, fn) ); }; // triggers when user clicks on thumbnail 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); // define options (if needed) options = { // 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 // http://photoswipe.com/documentation/faq.html#custom-pid-in-url 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'); ``` CodePen 示例(由于嵌入问题,禁用了 `focus`&`history` 选项): 提示:你可以从 CodePen 下载示例,以便在本地使用它(“在 CodePen 上编辑 `->`Share`->`Export .zip`)。 - 如果使用与本例不同的标记,则需要编辑函数`parseThumbnailElements`。 - 如果你对纯 JavaScript 没有经验,也不知道如何解析 DOM,请参考 [QuirksMode](http://quirksmode.org/dom/core/#gettingelements) 和 [documentation on MDN](https://developer.mozilla.org/en-US/docs/Web/API/Element.getElementsByTagName)。 - 注意,IE8 不支持 HTML5`
` 和 `
` 元素,因此你需要在 `` 部分中包含 [html5shiv](https://github.com/aFarkas/html5shiv)([CDNJS 托管版本](http://cdnjs.com/libraries/html5shiv/) 在示例中使用): ```html ``` ## 关于 请 [保持脚本更新](faq.html#keep-updated),通过 [GitHub](https://github.com/dimsemenov/PhotoSwipe) 报告错误,在 [UserVoice](https://photoswipe.uservoice.com/forums/275302-feature-requests-ideas) 上建议功能,并通过 [StackOverflow](http://stackoverflow.com/questions/ask?tags=javascript,photoswipe) 提问。 知道如何改进这个页面吗?找到了一个错别字?[建议编辑一下!](https://github.com/dimsemenov/PhotoSwipe/blob/master/website/documentation/getting-started.md)