移动端滑动

以你之姓@ 2022-05-30 08:45 404阅读 0赞

前言

移动端,滑动是很常见的需求。很多同学都用过swiper.js,本文从原理出发,实践出一个类swiper的滑动小插件ice-skating。

小插件的例子:

  • 移动端
  • pc端

在写代码的过程中产生的一些思考:

  • 滑动的原理是什么
  • 怎么判断动画完成
  • 事件绑定到哪个元素,可否使用事件委托优化
  • pc端和移动端滑动有何不同
  • 正在进行的动画触摸时怎么取得当前样式
  • 如何实现轮播

基本原理

滑动就是用transform: translate(x,y)或者transform: translate3d(x,y,z)去控制元素的移动,在松手的时候判定元素最后的位置,元素的样式应用transform: translate3d(endx , endy, 0)transition-duration: time来达到一个动画恢复的效果。标准浏览器提供transitionend事件监听动画结束,在结束时将动画时间归零。

Note: 这里不讨论非标准浏览器的实现,对于不支持transformtransition的浏览器,可以使用position: absolute配合lefttop进行移动,然后用基于时间的动画的算法来模拟动画效果。

html结构

举例一个基本的结构:

  1. //example <div class="ice-container"> <div class="ice-wrapper" id="myIceId"> <div class="ice-slide">Slide 1</div> <div class="ice-slide">Slide 2</div> <div class="ice-slide">Slide 3</div> </div> </div>

transform: translate3d(x,y,z)就是应用在className为ice-slide的元素上。这里不展示css代码,可以在ice-skating的example文件中里查看完整的css。css代码并不是唯一的,简单说只要实现下图的结构就可以。

861999-20170404155840738-1980032266.png

从图中可以直观的看出,移动的是绿色的元素。className为ice-slide的元素的宽乘于当前索引(offsetWidth * index),就是每次稳定时的偏移量。例如最开始transform: translate3d(offsetWidth * 0, 0, 0),切换到slide2后,transform: translate3d(offsetWidth * 1, 0, 0),大致就是这样的过程。

实践

源码位于ice-skating的dist/iceSkating.js。我给插件起名叫ice-skating,希望它像在冰面一样顺畅^_^

兼容各模块标准的容器

以前我们会将代码包裹在一个简单的匿名函数里,现在需要加一些额外的代码来兼容各种模块标准。

  1. (function (global, factory) {
  2. typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
  3. typeof define === 'function' && define.amd ? define(['exports'], factory) :
  4. (factory((global)));
  5. }(this, (function (exports) {
  6. 'use strict';
  7. })));

状态容器

用两个对象来存储信息

  • 一个页面可以实例化很多滑动对象,mainStore存储的是每个对象的信息,比如宽高,配置参数之类的。
  • state存储的是触摸之类的临时信息,每次触摸后都会清空。

    var mainStore = Object.create(null);
    var state = Object.create(null);

Object.create(null)创建的对象不会带有Object.prototype上的方法,因为我们不需要它们,例如toStringvalueOfhasOwnProperty之类的。

构造函数

  1. function iceSkating(option){
  2. if (!(this instanceof iceSkating)) return new iceSkating(option);
  3. }
  4. iceSkating.prototype = {
  5. }

if (!(this instanceof iceSkating)) return new iceSkating(option);很多库和框架都有这句,简单说就是不用new生成也可以生成实例。

触摸事件

对于触摸事件,在移动端,我们会用touchEvent,在pc端,我们则用mouseEvent。所以我们需要检测支持什么事件。

  1. iceSkating.prototype = {
  2. support: {
  3. touch: (function(){
  4. return !!(('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch);
  5. })()
  6. }

支持touch则认为是移动端,否则为pc端

  1. var events = ic.support.touch ? ['touchstart', 'touchmove', 'touchend']:['mousedown','mousemove','mouseup'];

声明事件函数

pc端和移动端这3个函数是通用的。

  1. var touchStart = function(e){};
  2. var touchMove = function(e){};
  3. var touchEnd = function(e){};

初始化事件

  1. var ic = this;
  2. var initEvent = function(){
  3. var events = ic.support.touch ? ['touchstart', 'touchmove', 'touchend']: ['mousedown','mousemove','mouseup'];
  4. var transitionEndEvents = ['webkitTransitionEnd', 'transitionend', 'oTransitionEnd', 'MSTransitionEnd', 'msTransitionEnd'];
  5. for (var i = 0; i < transitionEndEvents.length; i++) {
  6. ic.addEvent(container, transitionEndEvents[i], transitionDurationEndFn, false);
  7. }
  8. ic.addEvent(container, events[0], touchStart, false);
  9. //默认阻止容器元素的click事件
  10. if(ic.store.preventClicks) ic.addEvent(container, 'click', ic.preventClicks, false);
  11. if(!isInit){
  12. ic.addEvent(document, events[1], touchMove, false);
  13. ic.addEvent(document, events[2], touchEnd, false);
  14. isInit = true;
  15. }
  16. };

touchStarttransitionDurationEndFn函数每个实例的容器都会绑定,但是所有实例共用touchMovetouchEnd函数,它们只绑定在document,并且只会绑定一次。使用事件委托有两个好处:

  1. 减少了元素绑定的事件数,提高了性能。
  2. 如果将touchMovetouchEnd也绑定在容器元素上,当鼠标移出容器元素时,我们会“失去控制”。在document上意味着可以“掌控全局”。

过程分析

不会把封装的函数的代码都一一列出来,但会说明它的作用。

触碰瞬间

touchStart函数:

会在触碰的第一时间调用,基本都在初始化state的信息

  1. var touchStart = function(e){
  2. //mouse事件会提供which值, e.which为3时表示按下鼠标右键,鼠标右键会触发mouseup,但右键不允许移动滑块
  3. if (!ic.support.touch && 'which' in e && e.which === 3) return;
  4. //获取起始坐标。TouchEvent使用e.targetTouches[0].pageX,MouseEvent使用e.pageX。
  5. state.startX = e.type === 'touchstart' ? e.targetTouches[0].pageX : e.pageX;
  6. state.startY = e.type === 'touchstart' ? e.targetTouches[0].pageY : e.pageY;
  7. //时间戳
  8. state.startTime = e.timeStamp;
  9. //绑定事件的元素
  10. state.currentTarget = e.currentTarget;
  11. state.id = e.currentTarget.id;
  12. //触发事件的元素
  13. state.target = e.target;
  14. //获取当前滑块的参数信息
  15. state.currStore = mainStore[e.currentTarget.id];
  16. //state的touchStart 、touchMove、touchEnd代表是否进入该函数
  17. state.touchEnd = state.touchMove = false;
  18. state.touchStart = true;
  19. //表示滑块移动的距离
  20. state.diffX = state.diffY = 0;
  21. //动画运行时的坐标与动画运行前的坐标差值
  22. state.animatingX = state.animatingY = 0;
  23. };

移动

在移动滑块时,可能滑块正在动画中,这是需要考虑一种特殊情况。滑块的移动应该依据现在的位置计算。
如何知道动画运行中的信息呢,可以使用window.getComputedStyle(element, [pseudoElt]),它返回的样式是一个实时的CSSStyleDeclaration对象。用它取transform的值会返回一个 2D 变换矩阵,像这样matrix(1, 0, 0, 1, -414.001, 0),最后两位就是x,y值。

简单封装一下,就可以取得当前动画translate的x,y值了。

  1. var getTranslate = function(el){
  2. var curStyle = window.getComputedStyle(el);
  3. var curTransform = curStyle.transform || curStyle.webkitTransform;
  4. var x,y; x = y = 0;
  5. curTransform = curTransform.split(', ');
  6. if (curTransform.length === 6) {
  7. x = parseInt(curTransform[4], 10);
  8. y = parseInt(curTransform[5], 10);
  9. }
  10. return { 'x': x,'y': y};
  11. };

touchMove函数:

移动时会持续调用,如果只是点击操作,不会触发touchMove。

  1. var touchMove = function(e){
  2. // 1. 如果当前触发touchMove的元素和触发touchStart的元素不一致,不允许滑动。
  3. // 2. 执行touchMove时,需保证touchStart已执行,且touchEnd未执行。
  4. if(e.target !== state.target || state.touchEnd || !state.touchStart) return;
  5. state.touchMove = true;
  6. //取得当前坐标
  7. var currentX = e.type === 'touchmove' ? e.targetTouches[0].pageX : e.pageX;
  8. var currentY = e.type === 'touchmove' ? e.targetTouches[0].pageY : e.pageY;
  9. var currStore = state.currStore;
  10. //触摸时如果动画正在运行
  11. if(currStore.animating){
  12. // 取得当前元素translate的信息
  13. var animationTranslate = getTranslate(state.currentTarget);
  14. //计算动画的偏移量,currStore.translateX和currStore.translateY表示的是滑块最近一次稳定时的translate值
  15. state.animatingX = animationTranslate.x - currStore.translateX;
  16. state.animatingY = animationTranslate.y - currStore.translateY;
  17. currStore.animating = false;
  18. //移除动画时间
  19. removeTransitionDuration(currStore.container);
  20. }
  21. //如果轮播进行中,将定时器清除
  22. if(currStore.autoPlayID !== null){
  23. clearTimeout(currStore.autoPlayID);
  24. currStore.autoPlayID = null;
  25. }
  26. //判断移动方向是水平还是垂直
  27. if(currStore.direction === 'x'){
  28. //currStore.touchRatio是移动系数
  29. state.diffX = Math.round((currentX - state.startX) * currStore.touchRatio);
  30. //移动元素
  31. translate(currStore.container, state.animatingX + state.diffX + state.currStore.translateX, 0, 0);
  32. }else{
  33. state.diffY = Math.round((currentY - state.startY) * state.currStore.touchRatio);
  34. translate(currStore.container, 0, state.animatingY + state.diffY + state.currStore.translateY, 0);
  35. }
  36. };

translate函数:

如果支持translate3d,会优先使用它,translate3d会提供硬件加速。有兴趣可以看看这篇blog两张图解释CSS动画的性能

  1. var translate = function(ele, x, y, z){
  2. if (ic.support.transforms3d){
  3. transform(ele, 'translate3d(' + x + 'px, ' + y + 'px, ' + z + 'px)');
  4. } else {
  5. transform(ele, 'translate(' + x + 'px, ' + y + 'px)');
  6. }
  7. };

触摸结束

touchEnd函数:

在触摸结束时调用。

  1. var touchEnd = function(e){
  2. state.touchEnd = true;
  3. if(!state.touchStart) return;
  4. var fastClick ;
  5. var currStore = state.currStore;
  6. //如果整个触摸过程时间小于fastClickTime,会认为此次操作是点击。但默认是屏蔽了容器的click事件的,所以提供一个clickCallback参数,会在点击操作时调用。
  7. if(fastClick = (e.timeStamp - state.startTime) < currStore.fastClickTime && !state.touchMove && typeof currStore.clickCallback === 'function'){
  8. currStore.clickCallback();
  9. }
  10. if(!state.touchMove) return;
  11. //如果移动距离没达到切换页的临界值,则让它恢复到最近的一次稳定状态
  12. if(fastClick || (Math.abs(state.diffX) < currStore.limitDisX && Math.abs(state.diffY) < currStore.limitDisY)){
  13. //在transitionend事件绑定的函数中判定是否重启轮播,但是如果transform前后两次的值一样时,不会触发transitionend事件,所以在这里判定是否重启轮播
  14. if(state.diffX === 0 && state.diffY === 0 && currStore.autoPlay) autoPlay(currStore);
  15. //恢复到最近的一次稳定状态
  16. recover(currStore, currStore.translateX, currStore.translateY, 0);
  17. }else{
  18. //位移满足切换
  19. if(state.diffX > 0 || state.diffY > 0) {
  20. //切换到上一个滑块
  21. moveTo(currStore, currStore.index - 1);
  22. }else{
  23. //切换到下一个滑块
  24. moveTo(currStore, currStore.index + 1);
  25. }
  26. }
  27. };

transitionDurationEndFn函数:

动画执行完成后调用

  1. var transitionDurationEndFn = function(){
  2. //将动画状态设置为false
  3. ic.store.animating = false;
  4. //执行自定义的iceEndCallBack函数
  5. if(typeof ic.store.iceEndCallBack === 'function') ic.store.iceEndCallBack();
  6. //将动画时间归零
  7. transitionDuration(container, 0);
  8. //清空state
  9. if(ic.store.id === state.id) state = Object.create(null);
  10. };

至此,一个完整的滑动过程结束。

实现轮播

第一时间想到的是使用setInterval或者递归setTimeout实现轮播,但这样做并不优雅。

事件循环(EventLoop)中setTimeoutsetInterval会放入macrotask 队列中,里面的函数会放入microtask,当这个macrotask 执行结束后所有可用的 microtask将会在同一个事件循环中执行。

我们极端的假设setInterval设定为200ms,动画时间设为1000ms。每隔200ms, macrotask 队列中就会插入setInterval,但我们的动画此时没有完成,所以用setInterval或者递归setTimeout的轮播在这种情况下是有问题的。

最佳思路是在每次动画结束后再将轮播开启。

  1. 动画结束执行的函数:
  2. var transitionDurationEndFn = function(){
  3. ...
  4. //检测是否开启轮播
  5. if(ic.store.autoPlay) autoPlay(ic.store);
  6. };

轮播函数也相当简单

  1. var autoPlay = function(store){
  2. store.autoPlayID = setTimeout(function(){
  3. //当前滑块的索引
  4. var index = store.index;
  5. ++index;
  6. //到最后一个了,重置为0
  7. if(index === store.childLength){
  8. index = 0;
  9. }
  10. //移动
  11. moveTo(store, index);
  12. },store.autoplayDelay);

发表评论

表情:
评论列表 (有 0 条评论,404人围观)

还没有评论,来说两句吧...

相关阅读

    相关 移动滑动事件方法

    今天使用jquery.fullpage.js的时候,发现移动端调试不支持滑动事件,于是自己写了一个滑动的事件,如下,使用这个插件时只需要给window绑定一个滑动事件就可以了,

    相关 移动滑动

    前言 移动端,滑动是很常见的需求。很多同学都用过[swiper.js][],本文从原理出发,实践出一个类swiper的滑动小插件[ice-skating][]。 小插件