移動端滑屏 touch事件

移動端滑屏 touch事件

  移動端觸屏滑動的效果的效果在電子設備上已經被應用的越來越廣泛,類似於PC端的圖片輪播,但是在移動設備上,要實現這種輪播的效果,就需要用到核心的touch事件。處理touch事件能跟蹤到屏幕滑動的每根手指。

以下是四種touch事件

touchstart: //觸摸屏幕時觸發;即使已經有一個手指放在了屏幕上也會觸發。
touchmove: //在屏幕上滑動時連續的觸發。在這個事件發生期間,調用preventDefault()可阻止滾動。
touchend: //從屏幕上移開時觸發。
touchcancel: //系統取消touch事件的時候觸發,這個好像比較少用。
上面這幾個事件都會冒泡,也都可以取消。雖然這些觸摸事件沒有在DOM規範中定義,但它們卻是以兼容DOM的方式實現的。因此,每個觸摸事件沒有在DOM規範中定義,但它們卻是以兼容DOM的方式實現的。因此,每個觸摸事件的event對象都提供了在鼠標事件中常見的屬性:bubbles、cancelable、view、clientX、clientY、screenX、screenY、detail、altKey、shiftKey、ctrlKey和metaKey。

每個觸摸事件被觸發後,會生成一個event對象,event對象裏額外包括以下三個觸摸列表。
touches://表示當前跟蹤的觸摸操作的touch對象的數組。
當一個手指在觸屏上時,event.touches.length=1,
當兩個手指在觸屏上時,event.touches.length=2,以此類推。
targetTouches://特定於事件目標的touch對象數組。因爲touch事件是會冒泡的,所以利用這個屬性指出目標對象。
changedTouches://表示自上次觸摸以來發生了什麼改變的touch對象的數組。

這些列表裏的每次觸摸由touch對象組成,touch對象裏包含着觸摸信息,主要屬性如下:
clientX://觸摸目標在視口中的x座標。
clientY://觸摸目標在視口中的y座標。
identifier://標識觸摸的唯一ID。
pageX://觸摸目標在頁面中的x座標。
pageY://觸摸目標在頁面中的y座標。
screenX://觸摸目標在屏幕中的x座標。
screenY://觸摸目標在屏幕中的y座標。
target://觸摸的DOM節點目標。

注意事項:

手指在滑動整個屏幕時,會影響瀏覽器的行爲,比如滾動和縮放。所以在調用touch事件時,要注意禁止縮放和滾動。

1.禁止縮放

通過meta元標籤來設置。

<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1,minimum-scale=1,user-scalable=no">

加上這句代碼後,我們編寫的頁面將不會隨着用的手勢而放大縮小。

2.禁止滾動

preventDefault是阻止默認行爲,touch事件的默認行爲就是滾動。
由於觸摸會導致屏幕動來動去,所以可以會在這些事件的事件處理函數內使用event.preventDefault(),來阻止屏幕的默認滾動。

  這裏寫的demo的使用的方法是將HTML結構寫好後往裏傳參就可以了。它接受所有滑動頁面對象(在這裏是document.querySelector('#pages') ) 和要設定的方向(用X,Y表示橫向或者縱向)以及一個可選的擴展函數。

縱向滑屏案例
這裏將所有的代碼都封裝進一個PageSlide的原型對象中,可以當成原生JS插件來使用,

它所要求的HTML的結構爲

 
 

<div class="pages"> 
<div class="page page1">page1</div> 
<div class="page page2">page2<div class="myAnimation"></div></div>
<div class="page page3">page3</div>
<div class="page page4">page4</div>
<div class="page page5">page5</div>
<div class="page page6">page6</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 { font-size:100px; position: absolute; top: 0; left: 0; width: 100%; height: 100%; overflow: hidden; }

.page1{background:pink;}
.page2{background:lightgreen;}
.page3{background:skyblue;}
.page4{background:red;}
.page5{background:green;}
.page6{background:blue;}

/* the box 動畫 */
.box{ width:100px; height:100px; background:black; }

/* 所有動畫使用類控制 */
.play .myAnimation{ animation:move 1s ease 1 both; -webkit-animation: move 1s ease 1 both; }
@-webkit-keyframes move{
 100%{
   -webkit-transform:translate3d(150px,0,0);
   transform:translate3d(150px,0,0);
   -ms-transform: translate3d(150px,0,0);
 }
}

  要實現手指跟隨的滑動效果, 關鍵在於通過touch事件來設置transform:translate3d(x,y,z)的參數,並在滑動結束(touchend)設置一個最小滑動距離minRange,該距離範圍內的滑動,translate3d的參數等於touchmove的滑動距離,當大於minRange時, 則觸發下一頁(或上一頁)的整體滑動,translate3d的X或Y的參數也就是視窗的寬(橫向滑動時)或者高(縱向滑動時)。


  另外,對於一個網頁單頁,還需要解決一個問題,即每個頁面中可能有動畫或者其他的事件需要在該頁面出現時纔開始播放,動畫採用css類控制, 這裏採用在每個當前頁面中添加一個.play的類作爲標記, 在每個頁面的CSS動畫設置中,同樣加上.play類名,這樣就實現了當頁面出現纔開始播放本頁動畫的功能。


JavaScript的代碼如下

// 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];

    //觸控開始

    this.flag = null;

    this.move = 0;

    //記錄落點

    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;

    //添加移動樣式

    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);

};

//直達任意頁面的方法

/*直達某一頁面的方法, 因爲個人研究的需要,寫了這個方法,要從任意頁面開始滑動依然能保持正常的滑動體驗,就需要將直達頁面的前面所有頁面的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;

};

  // 傳參

document.addEventListener('touchmove', function(e) {

  e.preventDefault();

});

var pages = new PageSlide(document.querySelector('.pages'), 'Y', {

  tranSetionEnd: function() {

    console.log(this.current);

  }

});

案例演示:

橫向滑屏案例

橫向滑屏的思路與縱向的類似,在這個demo中只需要將傳入的參數由“Y”改爲“X”就可以了,

// 傳參 
document.addEventListener('touchmove', function(e) {
  e.preventDefault();
});
var pages = new PageSlide(document.querySelector('.pages'), 'X', {
  tranSetionEnd: function() {
    console.log(this.current);
  }
});

案例演示:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章