PhotoSwipe-一个好用的图片放大缩小插件

通过GitHub 下载PhotoSwipe https://github.com/dimsemenov/PhotoSwipe 相关的库

<link rel="stylesheet" href="css/photoswipe.css" />
<link rel="stylesheet" href="css/default-skin/default-skin.css" /> <script src="js/photoswipe.min.js"></script>
<script src="js/photoswipe-ui-default.js"></script>
<script src="js/connect.js"></script>
//引入相关的css和js文件及皮肤

connect.js

 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("");
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>");
//因为作者没有把相关的div放进js里,所以这边通过打印,具体可以观看官方文档得知为什么要这么做。
(function() { var initPhotoSwipeFromDOM = function(gallerySelector) { var parseThumbnailElements = function(el) {
var thumbElements = el.childNodes,
numNodes = thumbElements.length,
items = [],
el,
childElements,
thumbnailEl,
size,
item; for(var i = ; i < numNodes; i++) {
el = thumbElements[i]; // include only element nodes
if(el.nodeType !== ) {
continue;
} childElements = el.children; size = el.getAttribute('data-size').split('x'); // create slide object
item = {
src: el.getAttribute('href'),
w: parseInt(size[], ),
h: parseInt(size[], ),
author: el.getAttribute('data-author')
}; item.el = el; // save link to element for getThumbBoundsFn if(childElements.length > ) {
item.msrc = childElements[].getAttribute('src'); // thumbnail url
if(childElements.length > ) {
item.title = childElements[].innerHTML; // caption (contents of figure)
}
} var mediumSrc = el.getAttribute('data-med');
if(mediumSrc) {
size = el.getAttribute('data-med-size').split('x');
// "medium-sized" image
item.m = {
src: mediumSrc,
w: parseInt(size[], ),
h: parseInt(size[], )
};
}
// original image
item.o = {
src: item.src,
w: item.w,
h: item.h
}; items.push(item);
} return items;
}; // find nearest parent element
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; var clickedListItem = closest(eTarget, function(el) {
return el.tagName === 'A';
}); if(!clickedListItem) {
return;
} var clickedGallery = clickedListItem.parentNode; var childNodes = clickedListItem.parentNode.childNodes,
numChildNodes = childNodes.length,
nodeIndex = ,
index; for (var i = ; i < numChildNodes; i++) {
if(childNodes[i].nodeType !== ) {
continue;
} if(childNodes[i] === clickedListItem) {
index = nodeIndex;
break;
}
nodeIndex++;
} if(index >= ) {
openPhotoSwipe( index, clickedGallery );
}
return false;
}; var photoswipeParseHash = function() {
var hash = window.location.hash.substring(),
params = {}; if(hash.length < ) { // pid=1
return params;
} var vars = hash.split('&');
for (var i = ; i < vars.length; i++) {
if(!vars[i]) {
continue;
}
var pair = vars[i].split('=');
if(pair.length < ) {
continue;
}
params[pair[]] = pair[];
} if(params.gid) {
params.gid = parseInt(params.gid, );
} return params;
}; var openPhotoSwipe = function(index, galleryElement, disableAnimation, fromURL) {
var pswpElement = document.querySelectorAll('.pswp')[],
gallery,
options,
items; items = parseThumbnailElements(galleryElement); // define options (if needed)
options = { galleryUID: galleryElement.getAttribute('data-pswp-uid'), getThumbBoundsFn: function(index) {
// See Options->getThumbBoundsFn section of docs for more info
var thumbnail = items[index].el.children[],
pageYScroll = window.pageYOffset || document.documentElement.scrollTop,
rect = thumbnail.getBoundingClientRect(); return {x:rect.left, y:rect.top + pageYScroll, w:rect.width};
}, addCaptionHTMLFn: function(item, captionEl, isFake) {
if(!item.title) {
captionEl.children[].innerText = '';
return false;
}
captionEl.children[].innerHTML = item.title + '<br/><small>Photo: ' + item.author + '</small>';
return true;
} }; 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 = ; j < items.length; j++) {
if(items[j].pid == index) {
options.index = j;
break;
}
}
} else {
options.index = parseInt(index, ) - ;
}
} else {
options.index = parseInt(index, );
} // exit if index not found
if( isNaN(options.index) ) {
return;
} var radios = document.getElementsByName('gallery-style');
for (var i = , length = radios.length; i < length; i++) {
if (radios[i].checked) {
if(radios[i].id == 'radio-all-controls') { } else if(radios[i].id == 'radio-minimal-black') {
options.mainClass = 'pswp--minimal--dark';
options.barsSize = {top:,bottom:};
options.captionEl = false;
options.fullscreenEl = false;
options.shareEl = false;
options.bgOpacity = 0.85;
options.tapToClose = true;
options.tapToToggleControls = false;
}
break;
}
} if(disableAnimation) {
options.showAnimationDuration = ;
} // Pass data to PhotoSwipe and initialize it
gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options); // see: http://photoswipe.com/documentation/responsive-images.html
var realViewportWidth,
useLargeImages = false,
firstResize = true,
imageSrcWillChange; gallery.listen('beforeResize', function() { var dpiRatio = window.devicePixelRatio ? window.devicePixelRatio : ;
dpiRatio = Math.min(dpiRatio, 2.5);
realViewportWidth = gallery.viewportSize.x * dpiRatio; if(realViewportWidth >= || (!gallery.likelyTouchDevice && realViewportWidth > ) || screen.width > ) {
if(!useLargeImages) {
useLargeImages = true;
imageSrcWillChange = true;
} } else {
if(useLargeImages) {
useLargeImages = false;
imageSrcWillChange = true;
}
} if(imageSrcWillChange && !firstResize) {
gallery.invalidateCurrItems();
} if(firstResize) {
firstResize = false;
} imageSrcWillChange = false; }); gallery.listen('gettingData', function(index, item) {
if( useLargeImages ) {
item.src = item.o.src;
item.w = item.o.w;
item.h = item.o.h;
} else {
item.src = item.m.src;
item.w = item.m.w;
item.h = item.m.h;
}
}); gallery.init();
}; // select all gallery elements
var galleryElements = document.querySelectorAll( gallerySelector );
for(var i = , l = galleryElements.length; i < l; i++) {
galleryElements[i].setAttribute('data-pswp-uid', i+);
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 - ], true, true );
}
}; initPhotoSwipeFromDOM('.photoswipe'); })();

我们通过名为photoswipe的class通知要用到的子元素。

a里的图片为放大之后的图片,img里的图片为可实际查看的小图,data-size为要放大的图片大小。

 <div class="photoswipe">
<a href="img/1-max.jpeg" data-size='1000x1000' >
<img src="img/1-450.jpeg"/>
</a>
<a href="http://img3.imgtn.bdimg.com/it/u=4166721891,1503444760&fm=26&gp=0.jpg" data-size='1000x1000' >
<img src="http://img3.imgtn.bdimg.com/it/u=4166721891,1503444760&fm=26&gp=0.jpg"/>
</a>
<a href="http://www.91danji.com/attachments/201511/19/10/24kf5fidw.jpg" data-size='1000x1000' >
<img src="http://www.91danji.com/attachments/201511/19/10/24kf5fidw.jpg"/>
</a>
</div>

拓展:因项目需要,以及通过后台渲染出的图片大小或外链的图片,总不可能一个个设置data-size,于是用jQuery配合js写了几段代码。

 $(document).ready(function(){ //如果认为代码写的很乱可以自行修改
var pic=$("[data-size]");
pic.each(function(){
var _this = $(this);
var images = new Image(); //实例化图片
images.src = _this.find('img').attr('src'); //获取小图的链接 进行计算
images.onload = function(){ //当图片加载完
var tpW = images.width; //图片实际宽度
var tpH = images.height //图片实际高度
var winW = $(window).width(); //浏览器实际宽度
var winH = $(window).height(); //浏览器实际高度
var tpRatio = Math.min((winW/tpW),(winH/tpH));
var getW = tpW * tpRatio;
var getH = tpH * tpRatio; // 屏幕高度 * 图片宽度 / 图片高度
_this.attr("data-size",parseInt(getW,)+"x"+parseInt(getH,));
}
});
});

PhotoSwipe-一个好用的图片放大缩小插件

该插件是自适应的,具体可以通过谷歌浏览器查看该插件的炫酷之处。

上一篇:每周.NET前沿技术文章摘要(2017-05-17)


下一篇:11个强大的 Visual Studio 调试技能