美文网首页
swipe-js-ios 源码解析

swipe-js-ios 源码解析

作者: 没有颜色的菜 | 来源:发表于2019-07-20 14:38 被阅读0次

    前言

    Swipe,常用来做轮播图,需要翻页的场景,最经典的开源库 swipe-js-iso ,不过更推荐使用 React 组件 react-swipe,它封装了 swipe-js-ios 组件,而 swipe-js-ios 组件则封装了 Swipe

    HelloWord

    ReactSwipe

    如果单独使用的化,创建一个 swipe,dom 必须是三层结构,最里面一层是放 slide 的。

    <div id="slider" class="swipe">
      <div class="swipe-wrap">
        <div></div>
        <div></div>
        <div></div>
      </div>
    </div>
    

    CSS 子元素 float: left; container 的宽度为自定义,swipe-wrap 的宽度为子页面数 * container 的 width,每一个 slide 的宽度为 container 的 width

    .swipe {
      overflow: hidden;
      visibility: hidden;
      position: relative;
    }
    .swipe-wrap {
      overflow: hidden;
      position: relative;
    }
    .swipe-wrap > div {
      float: left;
      width: 100%;
      position: relative;
    }
    

    load 以后,创建 Swipe 即可

    const mySwipe = Swipe(document.getElementById('slider'));
    

    源码解析

    swipe-js-ios 使用立即函数导出了一个 Swipe 模块,使用 typeof module !== 'undefined' && module.exports 兼容 Node 和 浏览器环境,如果是 Node 环境,将会有 module.export 那么则使用 module.export 导出,否则使用 root.Swipe 全局变量导出

    (function(root, factory) {
      if (typeof module !== 'undefined' && module.exports) {
        module.exports = factory();
      } else {
        root.Swipe = factory();
      }
    })(this, function() {
      'use strict';
      return function Swipe(container, options) {
            ....
      };
    });
    

    检查浏览器的环境,算是一种规范吧,风别检查触摸事件和 transition 的支持
    ⚠️在浏览器,手机模式下,触摸事件是存在的,而普通浏览器下是不存在的,所以该组件不能在普通浏览器中使用。

    var browser = {
          addEventListener: !!window.addEventListener,
          touch:
            'ontouchstart' in window ||
            (window.DocumentTouch && document instanceof window.DocumentTouch),
          transitions: (function(temp) {
            var props = [
              'transitionProperty',
              'WebkitTransition',
              'MozTransition',
              'OTransition',
              'msTransition'
            ];
            for (var i in props)
              if (temp.style[props[i]] !== undefined) return true;
            return false;
          })(document.createElement('swipe'))
        };
    

    创建时会调用 setup,继而添加事件,touch 触摸事件、transitionend 移动事件,resize 重新布局事件

        // trigger setup
        setup();
    
        // start auto slideshow if applicable
        if (delay) begin();
    
        // add event listeners
        if (browser.addEventListener) {
          // set touchstart event on element
          if (browser.touch) {
            element.addEventListener('touchstart', events, false);
            element.addEventListener('touchforcechange', function() {}, false);
          }
    
          if (browser.transitions) {
            element.addEventListener('webkitTransitionEnd', events, false);
            element.addEventListener('msTransitionEnd', events, false);
            element.addEventListener('oTransitionEnd', events, false);
            element.addEventListener('otransitionend', events, false);
            element.addEventListener('transitionend', events, false);
          }
    
          // set resize event on window
          window.addEventListener('resize', events, false);
        } else {
          window.onresize = function() {
            setup();
          }; // to play nice with old IE
        }
    

    setup 函数的实现,slides 就是容器里面的页面,continuous 是否自动轮播,slidePos 记录了每一个页面的位置,width 是每一个页面的宽度,此处需要剪掉widthOfSiblingSlidePreview 的大小,可以预览前后页。element 的宽度是 **页数 * width **

    function setup() {
          // cache slides
          slides = element.children;
          length = slides.length;
    
          // set continuous to false if only one slide
          continuous = slides.length < 2 ? false : options.continuous;
    
          // create an array to store current positions of each slide
          slidePos = new Array(slides.length);
    
          // determine width of each slide
          width =
            Math.round(
              container.getBoundingClientRect().width || container.offsetWidth
            ) -
            widthOfSiblingSlidePreview * 2;
    
          element.style.width = slides.length * width + 'px';
        }
    

    初始化时,需要更新页面的位置

          var pos = slides.length;
          while (pos--) {
            var slide = slides[pos];
    
            slide.style.width = width + 'px';
            slide.setAttribute('data-index', pos);
    
            if (browser.transitions) {
              slide.style.left = pos * -width + widthOfSiblingSlidePreview + 'px';
              move(pos, index > pos ? -width : index < pos ? width : 0, 0);
            }
          }
    

    如果支持轮播的化,需要把左边和右边也填充,然后把 container.style.visibility 设置为 visible,如果不支持 transition 的话,只需要设置 element.style.left 即可

      // reposition elements before and after index
          if (continuous && browser.transitions) {
            move(circle(index - 1), -width, 0);
            move(circle(index + 1), width, 0);
          }
    
          if (!browser.transitions)
            element.style.left = index * -width + widthOfSiblingSlidePreview + 'px';
    
          container.style.visibility = 'visible';
    

    move 的实现,translate,更新 slidePos 的位置

        function move(index, dist, speed) {
          translate(index, dist, speed);
          slidePos[index] = dist;
        }
    

    translate 三个参数,index:需要移动的页,dist:移动的位置,speed:移动速度,移动只需要给 页面设置 style 的 transform 就OK了,之后就会以动画移动过去了

    function translate(index, dist, speed) {
          var slide = slides[index];
          var style = slide && slide.style;
    
          if (!style) return;
    
          style.webkitTransitionDuration = style.MozTransitionDuration = style.msTransitionDuration = style.OTransitionDuration = style.transitionDuration =
            speed + 'ms';
    
          style.webkitTransform = 'translate(' + dist + 'px,0)' + 'translateZ(0)';
          style.msTransform = style.MozTransform = style.OTransform =
            'translateX(' + dist + 'px)';
        }
    

    prev 对外提供接口,手动翻页使用

       function prev() {
          if (continuous) slide(index - 1);
          else if (index) slide(index - 1);
       }
    

    slide 移动函数,指定移动的页 index 和速度

    function slide(to, slideSpeed) {
          // do nothing if already on requested slide
          if (index == to) return;
    
          if (browser.transitions) {
            var direction = Math.abs(index - to) / (index - to); // 1: backward, -1: forward
    
            // get the actual position of the slide
            if (continuous) {
              var natural_direction = direction;
              direction = -slidePos[circle(to)] / width;
    
              // if going forward but to < index, use to = slides.length + to
              // if going backward but to > index, use to = -slides.length + to
              if (direction !== natural_direction)
                to = -direction * slides.length + to;
            }
    
            var diff = Math.abs(index - to) - 1;
    
            // move all the slides between index and to in the right direction
            while (diff--)
              move(
                circle((to > index ? to : index) - diff - 1),
                width * direction,
                0
              );
    
            to = circle(to);
    
            move(index, width * direction, slideSpeed || speed);
            move(to, 0, slideSpeed || speed);
    
            if (continuous) move(circle(to - direction), -(width * direction), 0); // we need to get the next in place
          } else {
            to = circle(to); 
            animate(index * -width, to * -width, slideSpeed || speed);
            //no fallback for a circular continuous if the browser does not accept transitions
          }
    
          index = to;
          offloadFn(options.callback && options.callback(index, slides[index]));
        }
    

    如果浏览器不支持 transition,那么则使用 setInterval 实现渐进移动, animation 是对整个页面进行移动,而 move 是移动每一个子页面

    function animate(from, to, speed) {
          // if not an animation, just reposition
          if (!speed) {
            element.style.left = to + 'px';
            return;
          }
    
          var start = +new Date();
    
          var timer = setInterval(function() {
            var timeElap = +new Date() - start;
    
            if (timeElap > speed) {
              element.style.left = to + 'px';
    
              if (delay) begin();
    
              options.transitionEnd &&
                options.transitionEnd.call(event, index, slides[index]);
    
              clearInterval(timer);
              return;
            }
    
            element.style.left =
              (to - from) * (Math.floor((timeElap / speed) * 100) / 100) +
              from +
              'px';
          }, 4);
        }
    

    接下来研究一下触摸事件的处理,首先是 start,start 事件会记录起始触摸位置以及时间,并且添加 touchmove 和 touchend 事件,如果没有 start 事件,触摸事件是不存在的, end 的时候会被移除。

    start: function(event) {
            var touches = event.touches[0];
    
            // measure start values
            start = {
              // get initial touch coords
              x: touches.pageX,
              y: touches.pageY,
    
              // store time to determine touch duration
              time: +new Date()
            };
    
            // used for testing first move event
            isScrolling = undefined;
    
            // reset delta and end measurements
            delta = {};
    
            // attach touchmove and touchend listeners
            element.addEventListener('touchmove', this, false);
            element.addEventListener('touchend', this, false);
          },
    

    move 事件,delta 将手指移动距离记下,最后视同 translate 移动

     move: function(event) {
            // ensure swiping with one touch and not pinching
            if (event.touches.length > 1 || (event.scale && event.scale !== 1))
              return;
    
            if (options.disableScroll) return;
    
            var touches = event.touches[0];
    
            // measure change in x and y
            delta = {
              x: touches.pageX - start.x,
              y: touches.pageY - start.y
            };
    
            // determine if scrolling test has run - one time test
            if (typeof isScrolling == 'undefined') {
              isScrolling = !!(
                isScrolling || Math.abs(delta.x) < Math.abs(delta.y)
              );
            }
    
            // if user is not trying to scroll vertically
            if (!isScrolling) {
              // prevent native scrolling
              event.preventDefault();
    
              // stop slideshow
              stop();
    
              // increase resistance if first or last slide
              if (continuous) {
                // we don't add resistance at the end
    
                translate(
                  circle(index - 1),
                  delta.x + slidePos[circle(index - 1)],
                  0
                );
                translate(index, delta.x + slidePos[index], 0);
                translate(
                  circle(index + 1),
                  delta.x + slidePos[circle(index + 1)],
                  0
                );
              } else {
                delta.x =
                  delta.x /
                  ((!index && delta.x > 0) || // if first slide and sliding left
                  (index == slides.length - 1 && // or if last slide and sliding right
                    delta.x < 0) // and if sliding at all
                    ? Math.abs(delta.x) / width + 1 // determine resistance level
                    : 1); // no resistance if false
    
                // translate 1:1
                translate(index - 1, delta.x + slidePos[index - 1], 0);
                translate(index, delta.x + slidePos[index], 0);
                translate(index + 1, delta.x + slidePos[index + 1], 0);
              }
              options.swiping && options.swiping(-delta.x / width);
            }
          },
    

    end 事件,主要判断本次触摸滑动是否有效,并持续接下来的操作,最后将会 remove 掉监听事件。

    end: function(event) {
            // measure duration
            var duration = +new Date() - start.time;
    
            // determine if slide attempt triggers next/prev slide
            var isValidSlide =
              (Number(duration) < 250 && // if slide duration is less than 250ms
                Math.abs(delta.x) > 20) || // and if slide amt is greater than 20px
              Math.abs(delta.x) > width / 2; // or if slide amt is greater than half the width
    
            // determine if slide attempt is past start and end
            var isPastBounds =
              (!index && delta.x > 0) || // if first slide and slide amt is greater than 0
              (index == slides.length - 1 && delta.x < 0); // or if last slide and slide amt is less than 0
    
            if (continuous) isPastBounds = false;
    
            // determine direction of swipe (true:right, false:left)
            var direction = delta.x < 0;
    
            // if not scrolling vertically
            if (!isScrolling) {
              if (isValidSlide && !isPastBounds) {
                if (direction) {
                  if (continuous) {
                    // we need to get the next in this direction in place
    
                    move(circle(index - 1), -width, 0);
                    move(circle(index + 2), width, 0);
                  } else {
                    move(index - 1, -width, 0);
                  }
    
                  move(index, slidePos[index] - width, speed);
                  move(
                    circle(index + 1),
                    slidePos[circle(index + 1)] - width,
                    speed
                  );
                  index = circle(index + 1);
                } else {
                  if (continuous) {
                    // we need to get the next in this direction in place
    
                    move(circle(index + 1), width, 0);
                    move(circle(index - 2), -width, 0);
                  } else {
                    move(index + 1, width, 0);
                  }
    
                  move(index, slidePos[index] + width, speed);
                  move(
                    circle(index - 1),
                    slidePos[circle(index - 1)] + width,
                    speed
                  );
                  index = circle(index - 1);
                }
    
                options.callback && options.callback(index, slides[index]);
              } else {
                if (continuous) {
                  move(circle(index - 1), -width, speed);
                  move(index, 0, speed);
                  move(circle(index + 1), width, speed);
                } else {
                  move(index - 1, -width, speed);
                  move(index, 0, speed);
                  move(index + 1, width, speed);
                }
              }
            }
    
            // kill touchmove and touchend event listeners until touchstart called again
            element.removeEventListener('touchmove', events, false);
            element.removeEventListener('touchend', events, false);
            element.removeEventListener('touchforcechange', function() {}, false);
          },
    

    总结

    总的来说,swipe-js-ios 充分利用了 transition,来实现移动动画,搞清楚触摸事件就比较容易能写出来可滑动的 swipe

    相关文章

      网友评论

          本文标题:swipe-js-ios 源码解析

          本文链接:https://www.haomeiwen.com/subject/eynqlctx.html