手机端点击图片放大特效PhotoSwipe.js插件实现

PhotoSwipe插件能实现手机端点击图片全屏放大 再双击图片放大等功能

PhotoSwipe插件官方网站 http://www.photoswipe.com/

但有一点不太好的是图片放大后再单击不能关闭浏览,要点击关闭按钮或者滑动才能关闭,找了好久配置项都没说到这点上的,只能自己动手改了。

打开photoswipe.js,大概在3179行有个关于tap的函数定义
在开头先定义一个变量

var tap_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

大概整体就是这样

var tapTimer,
 tapReleasePoint = {},
 _dispatchTapEvent = function(origEvent, releasePoint, pointerType) {
  var e = document.createEvent( 'CustomEvent' ),
   eDetail = {
    origEvent:origEvent,
    target:origEvent.target,
    releasePoint: releasePoint,
    pointerType:pointerType || 'touch'
   };

  e.initCustomEvent( 'pswpTap', true, true, eDetail );
  origEvent.target.dispatchEvent(e);
 };
var tap_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) {
    var p0 = releasePoint;
    if(tapTimer) {
     clearTimeout(tapTimer);
     tapTimer = null;

     // Check if taped on the same place
     if ( _isNearbyPoints(p0, tapReleasePoint) ) {
      _shout('doubleTap', p0);
      return;
     }
    }

    if(releasePoint.type === 'mouse') {
     _dispatchTapEvent(e, releasePoint, 'mouse');
     return;
    }

    var clickedTagName = e.target.tagName.toUpperCase();
    // avoid double tap delay on buttons and elements that have class pswp__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写上图片相册结构,并配上样式

<div id="demo-test-gallery" class="demo-gallery">
 <a href="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">
  <img src="https://farm4.staticflickr.com/3894/15008518202_b016d7d289_m.jpg" alt="" />
 </a>

 <a href="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">
  <img src="https://farm6.staticflickr.com/5591/15008867125_68a8ed88cc_m.jpg" alt="" />
 </a>
</div>

整理后的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("    <button class=\"pswp__button pswp__button--share\" title=\"Share\"><\/button>");
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>");

(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 = 0; i < numNodes; i++) {
     el = thumbElements[i];

     // include only element nodes
     if(el.nodeType !== 1) {
      continue;
     }

     childElements = el.children;

     size = el.getAttribute('data-size').split('x');

     // create slide object
     item = {
      src: el.getAttribute('href'),
      w: parseInt(size[0], 10),
      h: parseInt(size[1], 10),
      author: el.getAttribute('data-author')
     };

     item.el = el; // save link to element for getThumbBoundsFn

     if(childElements.length > 0) {
      item.msrc = childElements[0].getAttribute('src'); // thumbnail url
      if(childElements.length > 1) {
       item.title = childElements[1].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[0], 10),
       h: parseInt(size[1], 10)
      };
     }
     // 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 = 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) {
     openPhotoSwipe( index, clickedGallery );
    }
    return false;
   };

   var photoswipeParseHash = function() {
    var hash = window.location.hash.substring(1),
      params = {};

    if(hash.length < 5) { // pid=1
     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 = {

     galleryUID: galleryElement.getAttribute('data-pswp-uid'),

     getThumbBoundsFn: function(index) {
      // See Options->getThumbBoundsFn section of docs for more info
      var thumbnail = 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 = '';
       return false;
      }
      captionEl.children[0].innerHTML = item.title + '<br/><small>Photo: ' + item.author + '</small>';
      return true;
     }

    };

    // options for control bar
    options.shareEl = false;
    options.fullscreenEl = false;

    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 {
      options.index = parseInt(index, 10) - 1;
     }
    } else {
     options.index = parseInt(index, 10);
    }

    // exit if index not found
    if( isNaN(options.index) ) {
     return;
    }

    // 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 : 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();
   };

   // select all gallery elements
   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 );
   }
  };

  initPhotoSwipeFromDOM('.demo-gallery');

 })();

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • JS前端开发判断是否是手机端并跳转操作(小结)

    常用跳转代码 <script type="text/javascript"> // borwserRedirect (function browserRedirect(){ var sUserAgent = navigator.userAgent.toLowerCase(); var bIsIpad = sUserAgent.match(/ipad/i) == 'ipad'; var bIsIphone = sUserAgent.match(/iphone os/i) ==

  • 移动设备手势事件库Touch.js使用详解

    Touch.js手势库是专门在Webkit内核浏览器的移动设备中使用中设计的, Touch.js是移动设备上的手势识别与事件库.Touch.js基于原生事件,支持事件代理, 性能更好,极简的API,秒速上手等优势. 1.旋转事件- startRotate var angle = 0; touch.on('#target', 'touchstart', function(ev){ ev.startRotate(); ev.preventDefault(); }); touch.on('#targe

  • javascript移动设备Web开发中对touch事件的封装实例

    在触屏设备上,一些比较基础的手势都需要通过对 touch 事件进行二次封装才能实现. zepto 是移动端上使用率比较高的一个类库,但是其 touch 模块模拟出来的一些事件存在一些兼容性问题,如 tap 事件在某些安卓设备上存在事件穿透的 bug,其他类型的事件也或多或少的存在一些兼容性问题. 于是乎,干脆自己动手对这些常用的手势事件进行了封装,由于没有太多真实的设备来进行测试,可能存在一些兼容性问题,下面的代码也只是在 iOS 7.Andorid 4 上的一些比较常见的浏览器中测试通过. t

  • 浅谈移动端之js touch事件 手势滑动事件

    现分享一篇关于touch的文章,望指教! 原理: 当开始一个touchstart事件的时候,获取此刻手指的横坐标startX和纵坐标startY: 当触发touchmove事件时,在获取此时手指的横坐标moveEndX和纵坐标moveEndY;最后,通过这两次获取的坐标差值来判断手指在手机屏幕上的滑动方向. 具体代码如下: $("body").on("touchstart", function(e) { e.preventDefault(); startX = e.

  • 浅谈javascript的Touch事件

    js的touch事件,一般用于移动端的触屏滑动 复制代码 代码如下: $(function(){document.addEventListener("touchmove", _touch, false);}) function _touch(event){alert(1);} touchstart:当手指触摸屏幕时触发:即使已经有一个手指放在了屏幕上也会触发. touchmove:当手指在屏幕上滑动时连续的触发.在这个事件发生期间,调用preventDefault()可阻止滚动. to

  • JS模仿手机端九宫格登录功能实现代码

    最近没有项目做,闲来无事写了一个小demo,特此分享到我们平台,供大家参考下,本文写的不好还请各位大侠见谅! 功能及方法逻辑都注释在代码中.所以麻烦大家直接看代码. 效果如下: 话不多说直接上代码: js部分: 首先我们先画出两个九宫格,一个用于登录和首次设置滑动密码使用,另个用于再次设置滑动密码,用于与第一次输入的滑动密码进行对比,判断两次密码是否一致 第一个九宫格 $("#gesturepwd").GesturePasswd({ backgroundColor: "#25

  • JS手机端touch事件计算滑动距离的方法示例

    本文实例讲述了JS手机端touch事件计算滑动距离的方法.分享给大家供大家参考,具体如下: 计算手势在手机屏幕上滑动时,手势滑动的距离,代码如下: function wetherScroll(){ var startX = startY = endX =endY =0; var body=document.getElementsByTagName("body"); body.bind('touchstart',function(event){ var touch = event.tar

  • js的touch事件的实际引用

    一开始做前端页面的时候,接触的也是js,但是随后便被简单高效的jquery吸引过去,并一直使用至今. 而js,则被我主观的认为底层技术而抛弃. 直到这几天工作需要,研究移动端页面的触屏滑动事件,搜索jquery 的相应技术支持实在繁琐(当然也可能是我对jquery的理解不够),而js只需几步简单定义即可. 由于对js的了解比较少,最简单的应用我都试了很久--下面就分享下js的touch事件的实际引用: $(function(){ document.addEventListener("touchm

  • js实现touch移动触屏滑动事件

    移动端触屏滑动的效果其实就是图片轮播,在PC的页面上很好实现,绑定click和mouseover等事件来完成.但是在移动设备上,要实现这种轮播的效果,就需要用到核心的touch事件.处理touch事件能跟踪到屏幕滑动的每根手指. 以下是四种touch事件 touchstart: //手指放到屏幕上时触发 touchmove: //手指在屏幕上滑动式触发 touchend: //手指离开屏幕时触发 touchcancel: //系统取消touch事件的时候触发,这个好像比较少用 每个触摸事件被触发

  • javascript移动开发中touch触摸事件详解

    事件对象是用来记录一些事件发生时的相关信息的对象.事件对象只有事件发生时才会产生,并且只能是事件处理函数内部访问,在所有事件处理函数运行结束后,事件对象就被销毁! W3C DOM把事件对象作为事件处理函数的第一个参数传入进去 IE将事件对象作为window对象的一个属性(相当于全局变量) originalEvent对象 在一次偶然的使用中,我发现当使用on()函数并且传入第二个选择器参数时,e.touches[0]的访问为undefined,打印e发现,它的事件对象不是原生的事件对象.经查阅发现

随机推荐