web移動端觸摸滑動事件,web觸摸滑動事件
web移動端觸摸事件的範例~~~
注意:1.如果不是內嵌元素,擷取style的屬性值前需先賦值~不然為Null.2.親測andriod 手機 MX4內建瀏覽器運行妥妥的~~但是瀏覽器並不支援~原因未找到。
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" Content="text/html; charset=utf-8;"> 5 <title>web移動端觸摸滑動事件</title> 6 <meta name="description" content="web移動端觸摸滑動事件"/> 7 <meta name="viewport" content="user-scalable=no"> 8 </head> 9 <body>10 <div style="position:relative;left:10px;top:10px;height: 100px;width: 200px;background: blue;" id="slider"></div>11 <script>12 var slider = {13 //判斷裝置是否支援touch事件14 touch: ('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch,15 slider: document.getElementById('slider'),16 //事件17 events: {18 slider: this.slider, //this為slider對象19 handleEvent: function (event) {20 var self = this; //this指events對象21 if (event.type == 'touchstart') {22 self.start(event);23 } else if (event.type == 'touchmove') {24 self.move(event);25 } else if (event.type == 'touchend') {26 self.end(event);27 }28 },29 //touchstart30 start: function (event) {31 event.preventDefault(); //阻止瀏覽器的預設事件32 var touch = event.targetTouches[0]; //touches數組對象獲得螢幕上所有的touch,取第一個touch33 startPos = {x: touch.clientX, y: touch.clientY}; //取第一個touch的座標值34 sliderX = parseInt(this.slider.style.left); //擷取觸摸時滑動塊的初始位置35 sliderY = parseInt(this.slider.style.top);36 this.slider.addEventListener('touchmove', this, false);37 this.slider.addEventListener('touchend', this, false);38 },39 //touchmove40 move: function (event) {41 //當螢幕有多個touch或者頁面被縮放過,就不執行move操作42 if (event.targetTouches.length > 1 || event.scale && event.scale !== 1) return;43 var touch = event.targetTouches[0];44 endPos = {x: touch.clientX - startPos.x, y: touch.clientY - startPos.y}; //擷取所移動的距離45 event.preventDefault(); //阻止觸摸事件的預設行為,即阻止滾屏46 this.slider.style.left = (sliderX + endPos.x ) + 'px';47 this.slider.style.top = (sliderY + endPos.y) + 'px';48 49 },50 //滑動釋放51 end: function (event) {52 //解除綁定事件53 this.slider.removeEventListener('touchmove', this, false);54 this.slider.removeEventListener('touchend', this, false);55 }56 },57 58 //初始化59 init: function () {60 var self = this; //this指slider對象61 if (!!self.touch) self.slider.addEventListener('touchstart', self.events, false); //addEventListener第二個參數可以傳一個對象,會調用該對象的handleEvent屬性62 }63 };64 slider.init();65 </script>66 </body>67 </html>