挪动端原生JS完成手指追随的触控滑动

为了模仿原生运用的触控结果,大批的“H5”运用运用了手指追随的滑动结果,也就是用手指滑动幻灯片的结果, 什么是手指追随,如图;
《挪动端原生JS完成手指追随的触控滑动》

网上滑动插件有不少,但彷佛没一个好用的(不是bug太多,就是不天真)这里用原生JS完成了该功用,不仅代码量不多,逻辑也较简朴。挪动端H5页面的触控触发事宜在我之前的一篇博客中写了挺多.原博地点原生JS完成触控滑动(swipe)图片轮播 (内里大抵罗列了HTML5中touch事宜的运用要领)

这里写的PageSlide的运用的要领是将HTML构造写好后往里传参就能够了.它吸收一切滑动页面对象(在这里是document.querySelector(‘#pages’) ) 和要设定的方向(用X,Y示意横向或许纵向)以及一个可选的扩大函数.
DEMO在此(运用模仿器或许挪动装备翻开预览):
挪动端原生JS完成手指追随的触控滑动(纵向)
挪动端原生JS完成手指追随的触控滑动(横向)

直接下载代码出门左转Github? PageSlideDemo

扫码看DEMO(纵向):
《挪动端原生JS完成手指追随的触控滑动》
这里将一切的代码都封装进一个PageSlide的原型对象中,能够当做原生JS插件来运用,它所请求的HTML的构造为:

<div class='pages' id='pages'> // 一切滑动页面的容器
     <div class='page page1'>content</div>   //一切滑动单页
     <div class='page page2'><div class="myAnimation">animation element</div></div>
     ...
 </div>

CSS款式构造为:

/* 注重加html标签,使得高度100%即是视窗高度 */
html,body{
  width:100%;
  height:100%;
  margin:0 ;
  padding:0 ;
  overflow:hidden; 
  ……
}

.pages{
    width: 100%;
    height: 100%;
    position: relative;
    ……
  
}
.page {
/*滑动页面的一致款式 */
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    overflow: hidden;
    transform: translate3d(0px, 100%, 0px);
    -webkit-transform: translate3d(0px, 100%, 0px);
    transition: transform .5s ease-out;
    -webkit-transition: -webkit-transform .5s ease-out;
    
}
.page1{……}
.page2{……}
.page3{……}
/* 一切动画运用类掌握 */
.play .myAnimation {

...


}

要完成手指追随的滑动结果, 症结在于经由过程touch事宜来设置transform:translate3d(x,y,z)的参数,并在滑动完毕(touchend)设置一个最小滑动间隔minRange,该间隔范围内的滑动,translate3d的参数即是touchmove的滑动间隔,当大于minRange时, 则触发下一页(或上一页)的团体滑动,translate3d的X或Y的参数也就是视窗的宽(横向滑动时)或许高(纵向滑动时)

别的,关于一个网页app,还须要处理一个题目,即每一个页面中可能有动画或许其他的事宜须要在该页面涌现时才最先播放,动画采纳css类掌握, 这里采纳在每一个当前页面中增加一个.play的类作为标记, 在每一个页面的CSS动画设置中,一样加上.play类名,如许就完成了当页面涌现才最先播放本页动画的功用。

PageSlide的代码剖析以下:


// PageSlide吸收三个参数:页面元素,要设定的滑动方向,可选的扩大函数
var PageSlide = function(el, swipe, options) {
    this.options = options || {}  //可选函数
    this.current = 0  //当前页面索引
    this.pageX  //横向的手指落点
    this.pageY   //纵向的手指落点
    this.height //装备高度
    this.width   //装备宽度
    this.flag  //推断滑动方向的变量
    this.move  //滑动的间隔

    this.$el = el //当前页面的对象
    this.swipe = swipe || 'X' //滑动方向参数
    this.resize().init().bindEvents() //初始化
}


PageSlide.prototype.init = function(i) {
    var current = i ? this.$el.children[i] : this.$el.firstElementChild
    if (!current) throw 'ERROR';
//moving类名作为当前滑动页面的标记,也在款式中作滑动的扩大结果
    current.classList.add('moving')
    current.style.webkitTransform = 'translate3d(0,0,0)'
//以swipe的值预设置其他页面的宽高,取得流通的交互结果
for(var i = 1; i <this.$el.children.length ; i++){
        this['set' + this.swipe](this.$el.children[i],  (this.swipe === 'X' ? this.width : this.height)) 
        }
    setTimeout(function() {
        current.classList.remove('moving')
        current.classList.add('play')
    }, 3e2)
    return this
}

//为页面绑定种种事宜的绑定函数
PageSlide.prototype.bindEvents = function() {
    var self = this

    window.addEventListener('resize orientationchange', this.resize.bind(this), false)

    'touchstart touchmove touchend touchcancel'.split(' ').forEach(function(evn) {
   //将四个触控函数(说明在后面)绑定到每一个页面
        self.$el.addEventListener(evn, self[evn].bind(self), false)
    })
}
//取得当前触控的页面对象
PageSlide.prototype.getCurrent = function() {
    return this.$el.children[this.current]
}
//初始化时取得装备的宽高
PageSlide.prototype.resize = function() {
    this.width = this.$el.parentNode.clientWidth
    this.height = this.$el.parentNode.clientHeight
    return this
}
//抵达恣意页面的random()要领
PageSlide.prototype.random = function() {
    var count = this.$el.children.length
    var current = this.current
    var arr = []
    var num

    for (var i = 0; i < count; i++) {
        if (i !== current) arr.push(i.toString())
    }

    num = Math.floor(Math.random() * arr.length)
    this.direct(+arr[num])
}
// 四个内建的滑动事宜函数,与前面绑定函数相照应
PageSlide.prototype.touchstart = function(e) {
    var touches = e.touches[0]

    //touch start initializing
    this.flag = null
    this.move = 0

    //record coordinates
    this.pageX = touches.pageX
    this.pageY = touches.pageY
}

PageSlide.prototype.touchmove = function(e) {
    var touches = e.touches[0]
    var X = touches.pageX - this.pageX
    var Y = touches.pageY - this.pageY
    var current = this.getCurrent()
    var next = current.nextElementSibling
    var prev = current.previousElementSibling

    //add moving styled

    if (!this.flag) {
        this.flag = Math.abs(X) > Math.abs(Y) ? 'X' : 'Y'

        if (this.flag === this.swipe) {
            current.classList.add('moving')
            next && next.classList.add('moving')
            prev && prev.classList.add('moving')
        }
    }

    if (this.flag === this.swipe) {
        e.preventDefault()
        e.stopPropagation()

        switch (this.swipe) {
            case 'X':
                //swipe horizontal
                this.move = X

                this.setX(current, X)
                next && (this.setX(next, X + this.width))
                prev && (this.setX(prev, X - this.width))
                break;
            case 'Y':
                //swipe vertical
                this.move = Y

                this.setY(current, Y)
                next && (this.setY(next, Y + this.height))
                prev && (this.setY(prev, Y - this.height))
                break;
        }
    }
}

PageSlide.prototype.touchend = function(e) {
    var minRange = 50
    var move = this.move
    var current = this.getCurrent()
    var next = current.nextElementSibling
    var prev = current.previousElementSibling

    current.classList.remove('moving')
    next && next.classList.remove('moving')
    prev && prev.classList.remove('moving')
    if (!this.flag) return

    e.preventDefault()
   //滑动完毕前去下一页面,next()要领挪用了go()要领
    if (move < -minRange && next) return this.next()
    if (move > minRange && prev) return this.prev()
    this.reset()
}

PageSlide.prototype.touchcancel = function(e) {
    var current = this.getCurrent()
    var next = current.nextElementSibling
    var prev = current.previousElementSibling

    current.classList.remove('moving')
    next && next.classList.remove('moving')
    prev && prev.classList.remove('moving')
    this.reset()
}

//动态设定translate3d参数要领
PageSlide.prototype.setX = function(el, x, unit) {
    el && (el.style.webkitTransform = 'translate3d(' + x + (unit || 'px') + ',0,0)')
}

PageSlide.prototype.setY = function(el, y, unit) {
    el && (el.style.webkitTransform = 'translate3d(0,' + y + (unit || 'px') + ',0)')
}
//设置当前触控页面translate3d参数为0的要领
PageSlide.prototype.setCurrent = function(el, i) {
    el && (el.style.webkitTransform = 'translate3d(0,0,0)')

    if (i) {
        this.current = i
        this.$current = this.$el.children[i]
    }

}
//挪用go()要领前去下一或上一页面
PageSlide.prototype.next = function() {
    this.go(this.current + 1)
}

PageSlide.prototype.prev = function() {
    this.go(this.current - 1)
}
//重置要领,用于初始化以及当前页面的重置
PageSlide.prototype.reset = function() {
    var width = this.width
    var height = this.height
    var swipe = this.swipe
    var current = this.getCurrent()
    var prev = current.previousElementSibling
    var next = current.nextElementSibling

    this.setCurrent(current)
    prev && (this['set' + swipe](prev, -(swipe === 'X' ? width : height)))
    next && (this['set' + swipe](next, swipe === 'X' ? width : height))
}
//去往下一或上一页面的go要领
PageSlide.prototype.go = function(i) {
    var onFinish = this.options.onFinish
    var current = this.getCurrent()
    var total = this.$el.childElementCount
    var target = this.$el.children[i]
    var d = i < this.current ? -1 : 1


    if (i === this.current || i < 0 || i >= total) return
    if (onFinish && (typeof onFinish === 'function')) onFinish.call(this, i)
    // 滑动完成挪用要领
    typeof this.options.tranSetionEnd ==='function' && this.options.tranSetionEnd.call(this)
    this.current = i

    this['set' + this.swipe](current, -d * (this.swipe === 'X' ? this.width : this.height))
    this.setCurrent(target, i)
    this.finish(current, target)
}
//滑动完成后删除当前页面.play标记以及为下一页面增加.play标记
PageSlide.prototype.finish = function(curr, target) {
    this.flag = null
    setTimeout(function() {
        curr && curr.classList.remove('play')
        target && target.classList.add('play')
    }, 3e2)
}

/*direct to a page */ 
//直达某一页面的要领, 由于有个项目的须要,写了这个要领,要从恣意页面最先滑动依旧能坚持一般的滑动体验,就须要将直达页面的前面一切页面的translate3d参数都设置为(0,-height,0)  
PageSlide.prototype.direct = function(i){
    if(i&&typeof(i)==='number') 
       { 
       this.go(i) 
    for(var j = 0; j< i ;j++) {
        this['set' + this.swipe](this.$el.children[j], -1 * (this.swipe === 'X' ? this.width : this.height))       
        }
       }
    else  return
        
    
    }



总算写完了,用饭~

    原文作者:囧囧
    原文地址: https://segmentfault.com/a/1190000003817077
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞