手机端点击图片放大特效PhotoSwipe.js插件实现
PhotoSwipe插件能实现手机端点击图片全屏放大再双击图片放大等功能
PhotoSwipe插件官方网站http://www.photoswipe.com/
但有一点不太好的是图片放大后再单击不能关闭浏览,要点击关闭按钮或者滑动才能关闭,找了好久配置项都没说到这点上的,只能自己动手改了。
打开photoswipe.js,大概在3179行有个关于tap的函数定义
在开头先定义一个变量
vartap_num=0;
然后在onTapStart的定义里加入
//根据需求自己添加的S //判断是单击还是双击单击关闭双击放大 tap_num++; if(tap_num<2){ setTimeout(function(){ if(tap_num>1){ tap_num=0; return; }else{ tap_num=0; //判断是否有拖拽如有拖拽触发拖拽事件没有则关闭 if(_isDragging){ return; }else{ self.close(); } } },200); } //根据需求自己添加的E
大概整体就是这样
vartapTimer, tapReleasePoint={}, _dispatchTapEvent=function(origEvent,releasePoint,pointerType){ vare=document.createEvent('CustomEvent'), eDetail={ origEvent:origEvent, target:origEvent.target, releasePoint:releasePoint, pointerType:pointerType||'touch' }; e.initCustomEvent('pswpTap',true,true,eDetail); origEvent.target.dispatchEvent(e); }; vartap_num=0; _registerModule('Tap',{ publicMethods:{ initTap:function(){ _listen('firstTouchStart',self.onTapStart); _listen('touchRelease',self.onTapRelease); _listen('destroy',function(){ tapReleasePoint={}; tapTimer=null; }); }, onTapStart:function(touchList){ if(touchList.length>1){ clearTimeout(tapTimer); tapTimer=null; } //根据需求自己添加的S //判断是单击还是双击单击关闭双击放大 tap_num++; if(tap_num<2){ setTimeout(function(){ if(tap_num>1){ tap_num=0; return; }else{ tap_num=0; //判断是否有拖拽如有拖拽触发拖拽事件没有则关闭 if(_isDragging){ return; }else{ self.close(); } } },200); } //根据需求自己添加的E }, onTapRelease:function(e,releasePoint){ if(!releasePoint){ return; } if(!_moved&&!_isMultitouch&&!_numAnimations){ varp0=releasePoint; if(tapTimer){ clearTimeout(tapTimer); tapTimer=null; //Checkiftapedonthesameplace if(_isNearbyPoints(p0,tapReleasePoint)){ _shout('doubleTap',p0); return; } } if(releasePoint.type==='mouse'){ _dispatchTapEvent(e,releasePoint,'mouse'); return; } varclickedTagName=e.target.tagName.toUpperCase(); //avoiddoubletapdelayonbuttonsandelementsthathaveclasspswp__single-tap if(clickedTagName==='BUTTON'||framework.hasClass(e.target,'pswp__single-tap')){ _dispatchTapEvent(e,releasePoint); return; } _equalizePoints(tapReleasePoint,p0); tapTimer=setTimeout(function(){ _dispatchTapEvent(e,releasePoint); tapTimer=null; },300); } } } });
把修改后的photoswipe.js压缩一下,就能实现自己想要的功能了
另外,使用photoswipe插件需要插入框架和JavaScript代码,可以把这些代码整合成一个js再引入,这样页面看起来就简洁了很多。
先在html写上图片相册结构,并配上样式
<divid="demo-test-gallery"class="demo-gallery"> <ahref="https://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.jpg"data-size="1600x1600"data-med="https://farm4.staticflickr.com/3894/15008518202_b016d7d289_b.jpg"data-med-size="1024x1024"> <imgsrc="https://farm4.staticflickr.com/3894/15008518202_b016d7d289_m.jpg"alt=""/> </a> <ahref="https://farm6.staticflickr.com/5591/15008867125_b61960af01_h.jpg"data-size="1600x1068"data-med="https://farm6.staticflickr.com/5591/15008867125_68a8ed88cc_b.jpg"data-med-size="1024x1024"> <imgsrc="https://farm6.staticflickr.com/5591/15008867125_68a8ed88cc_m.jpg"alt=""/> </a> </div>
整理后的js
document.writeln("<!--RootelementofPhotoSwipe.Musthaveclasspswp.-->"); document.writeln("<divclass=\"pswp\"tabindex=\"-1\"role=\"dialog\"aria-hidden=\"true\">"); document.writeln(""); document.writeln("<!--BackgroundofPhotoSwipe."); document.writeln("It\'saseparateelementasanimatingopacityisfasterthanrgba().-->"); document.writeln("<divclass=\"pswp__bg\"><\/div>"); document.writeln(""); document.writeln("<!--Slideswrapperwithoverflow:hidden.-->"); document.writeln("<divclass=\"pswp__scroll-wrap\">"); document.writeln(""); document.writeln("<!--Containerthatholdsslides."); document.writeln("PhotoSwipekeepsonly3ofthemintheDOMtosavememory."); document.writeln("Don\'tmodifythese3pswp__itemelements,dataisaddedlateron.-->"); document.writeln("<divclass=\"pswp__container\">"); document.writeln("<divclass=\"pswp__item\"><\/div>"); document.writeln("<divclass=\"pswp__item\"><\/div>"); document.writeln("<divclass=\"pswp__item\"><\/div>"); document.writeln("<\/div>"); document.writeln(""); document.writeln("<!--Default(PhotoSwipeUI_Default)interfaceontopofslidingarea.Canbechanged.-->"); document.writeln("<divclass=\"pswp__uipswp__ui--hidden\">"); document.writeln(""); document.writeln("<divclass=\"pswp__top-bar\">"); document.writeln(""); document.writeln("<!--Controlsareself-explanatory.Ordercanbechanged.-->"); document.writeln(""); document.writeln("<divclass=\"pswp__counter\"><\/div>"); document.writeln(""); document.writeln("<buttonclass=\"pswp__buttonpswp__button--close\"title=\"Close(Esc)\"><\/button>"); document.writeln(""); document.writeln("<buttonclass=\"pswp__buttonpswp__button--share\"title=\"Share\"><\/button>"); document.writeln(""); document.writeln("<buttonclass=\"pswp__buttonpswp__button--fs\"title=\"Togglefullscreen\"><\/button>"); document.writeln(""); document.writeln("<buttonclass=\"pswp__buttonpswp__button--zoom\"title=\"Zoomin\/out\"><\/button>"); document.writeln(""); document.writeln("<!--Preloaderdemohttp:\/\/codepen.io\/dimsemenov\/pen\/yyBWoR-->"); document.writeln("<!--elementwillgetclasspswp__preloader--activewhenpreloaderisrunning-->"); document.writeln("<divclass=\"pswp__preloader\">"); document.writeln("<divclass=\"pswp__preloader__icn\">"); document.writeln("<divclass=\"pswp__preloader__cut\">"); document.writeln("<divclass=\"pswp__preloader__donut\"><\/div>"); document.writeln("<\/div>"); document.writeln("<\/div>"); document.writeln("<\/div>"); document.writeln("<\/div>"); document.writeln(""); document.writeln("<divclass=\"pswp__share-modalpswp__share-modal--hiddenpswp__single-tap\">"); document.writeln("<divclass=\"pswp__share-tooltip\"><\/div>"); document.writeln("<\/div>"); document.writeln(""); document.writeln("<buttonclass=\"pswp__buttonpswp__button--arrow--left\"title=\"Previous(arrowleft)\">"); document.writeln("<\/button>"); document.writeln(""); document.writeln("<buttonclass=\"pswp__buttonpswp__button--arrow--right\"title=\"Next(arrowright)\">"); document.writeln("<\/button>"); document.writeln(""); document.writeln("<divclass=\"pswp__caption\">"); document.writeln("<divclass=\"pswp__caption__center\"><\/div>"); document.writeln("<\/div>"); document.writeln(""); document.writeln("<\/div>"); document.writeln(""); document.writeln("<\/div>"); document.writeln(""); document.writeln("<\/div>"); (function(){ varinitPhotoSwipeFromDOM=function(gallerySelector){ varparseThumbnailElements=function(el){ varthumbElements=el.childNodes, numNodes=thumbElements.length, items=[], el, childElements, thumbnailEl, size, item; for(vari=0;i<numNodes;i++){ el=thumbElements[i]; //includeonlyelementnodes if(el.nodeType!==1){ continue; } childElements=el.children; size=el.getAttribute('data-size').split('x'); //createslideobject item={ src:el.getAttribute('href'), w:parseInt(size[0],10), h:parseInt(size[1],10), author:el.getAttribute('data-author') }; item.el=el;//savelinktoelementforgetThumbBoundsFn if(childElements.length>0){ item.msrc=childElements[0].getAttribute('src');//thumbnailurl if(childElements.length>1){ item.title=childElements[1].innerHTML;//caption(contentsoffigure) } } varmediumSrc=el.getAttribute('data-med'); if(mediumSrc){ size=el.getAttribute('data-med-size').split('x'); //"medium-sized"image item.m={ src:mediumSrc, w:parseInt(size[0],10), h:parseInt(size[1],10) }; } //originalimage item.o={ src:item.src, w:item.w, h:item.h }; items.push(item); } returnitems; }; //findnearestparentelement varclosest=functionclosest(el,fn){ returnel&&(fn(el)?el:closest(el.parentNode,fn)); }; varonThumbnailsClick=function(e){ e=e||window.event; e.preventDefault?e.preventDefault():e.returnValue=false; vareTarget=e.target||e.srcElement; varclickedListItem=closest(eTarget,function(el){ returnel.tagName==='A'; }); if(!clickedListItem){ return; } varclickedGallery=clickedListItem.parentNode; varchildNodes=clickedListItem.parentNode.childNodes, numChildNodes=childNodes.length, nodeIndex=0, index; for(vari=0;i<numChildNodes;i++){ if(childNodes[i].nodeType!==1){ continue; } if(childNodes[i]===clickedListItem){ index=nodeIndex; break; } nodeIndex++; } if(index>=0){ openPhotoSwipe(index,clickedGallery); } returnfalse; }; varphotoswipeParseHash=function(){ varhash=window.location.hash.substring(1), params={}; if(hash.length<5){//pid=1 returnparams; } varvars=hash.split('&'); for(vari=0;i<vars.length;i++){ if(!vars[i]){ continue; } varpair=vars[i].split('='); if(pair.length<2){ continue; } params[pair[0]]=pair[1]; } if(params.gid){ params.gid=parseInt(params.gid,10); } returnparams; }; varopenPhotoSwipe=function(index,galleryElement,disableAnimation,fromURL){ varpswpElement=document.querySelectorAll('.pswp')[0], gallery, options, items; items=parseThumbnailElements(galleryElement); //defineoptions(ifneeded) options={ galleryUID:galleryElement.getAttribute('data-pswp-uid'), getThumbBoundsFn:function(index){ //SeeOptions->getThumbBoundsFnsectionofdocsformoreinfo varthumbnail=items[index].el.children[0], 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[0].innerText=''; returnfalse; } captionEl.children[0].innerHTML=item.title+'<br/><small>Photo:'+item.author+'</small>'; returntrue; } }; //optionsforcontrolbar options.shareEl=false; options.fullscreenEl=false; if(fromURL){ if(options.galleryPIDs){ //parserealindexwhencustomPIDsareused //http://photoswipe.com/documentation/faq.html#custom-pid-in-url for(varj=0;j<items.length;j++){ if(items[j].pid==index){ options.index=j; break; } } }else{ options.index=parseInt(index,10)-1; } }else{ options.index=parseInt(index,10); } //exitifindexnotfound if(isNaN(options.index)){ return; } //PassdatatoPhotoSwipeandinitializeit gallery=newPhotoSwipe(pswpElement,PhotoSwipeUI_Default,items,options); //see:http://photoswipe.com/documentation/responsive-images.html varrealViewportWidth, useLargeImages=false, firstResize=true, imageSrcWillChange; gallery.listen('beforeResize',function(){ vardpiRatio=window.devicePixelRatio?window.devicePixelRatio:1; dpiRatio=Math.min(dpiRatio,2.5); realViewportWidth=gallery.viewportSize.x*dpiRatio; if(realViewportWidth>=1200||(!gallery.likelyTouchDevice&&realViewportWidth>800)||screen.width>1200){ 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(); }; //selectallgalleryelements vargalleryElements=document.querySelectorAll(gallerySelector); for(vari=0,l=galleryElements.length;i<l;i++){ galleryElements[i].setAttribute('data-pswp-uid',i+1); galleryElements[i].onclick=onThumbnailsClick; } //ParseURLandopengalleryifitcontains#&pid=3&gid=1 varhashData=photoswipeParseHash(); if(hashData.pid&&hashData.gid){ openPhotoSwipe(hashData.pid,galleryElements[hashData.gid-1],true,true); } }; initPhotoSwipeFromDOM('.demo-gallery'); })();
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。