标签:
常规写一段滑动代码,我们可能这么写
initEvent: function () { this.el.addEventListener("touchstart", this.touchStart.bind(this)); this.el.addEventListener("touchmove", this.touchMove.bind(this)); this.el.addEventListener("touchend", this.touchEnd.bind(this)); }, touchStart: function (e) { var touches = e.touches[0]; this.startStatus = { x: touches.pageX, time: Date.now() } this.validSlide = false; }, touchMove: function (e) { var touches = e.touches[0]; e.preventDefault(); this.endStatus = { x: touches.pageX, time: Date.now() } this.delta = { x: this.endStatus.x - this.startStatus.x, time: this.endStatus.time - this.startStatus.time } this.translate(this.delta.x + ‘px‘, 0); this.validSlide = true; }, touchEnd: function (e) { if (this.validSlide) { var deltaX = Math.abs(this.delta.x), dir = this.delta.x / deltaX, con = (deltaX > window.innerWidth / 3 || this.delta.time < 250 && deltaX > 20) && ((this.delta.x > 0 && this.el.querySelector(‘.prev‘)) || (this.delta.x < 0 && this.el.querySelector(‘.next‘))); if (con) { this.translate(dir * window.innerWidth + ‘px‘, this.speed); setTimeout(function () { window.s.trigger(‘slide‘, [dir]); }, this.speed); } else { this.translate(‘0px‘, this.speed); } } },
直接复制粘贴,请忽视相关业务代码。一般在touchmove中加e.preventDefault()来防止安卓手机只触发一次move和不触发end事件的问题。
但是这样还是会在安卓部分机型,例如三星手机中出现不触发touch事件的问题,具体的hack方法就是给document也绑定一个touchmove事件来阻止浏览器默认动作
document.addEventListener("touchmove", function (e) { e.preventDefault();});
标签:
原文地址:http://www.cnblogs.com/childsplay/p/5477328.html