①touch是移動端的觸摸事件,並且是一組事件,主要有如下事件:html
②利用touch相關事件能夠實現移動端常見的滑動效果和移動端常見的手勢事件,比較經常使用的事件主要是touchstart、touchmove、touchend,而且通常是使用addEventListener綁定事件dom
dom.addEventListener('touchstart',function(){ }); dom.addEventListener('touchmove',function(){ }); dom.addEventListener('touchend',function(){ });
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>touch事件</title> <style> .body{ margin: 0; padding: 0; } .box{ width: 200px; height: 200px;background: #ccc; float: left; } </style> </head> <body> <div class="box"></div> <script> window.onload=function(){ var box=document.querySelector('.box'); box.addEventListener('touchstart',function(){ console.log('start') }); box.addEventListener('touchmove',function(){ console.log('move') }); box.addEventListener('touchend',function(){ console.log('end') }); } </script> </body> </html>
①讓觸摸的元素隨着手指的滑動作位置的改變函數
②位置的改變,須要當前的座標,當前手指的座標和移動後的座標均可以在事件對象中拿到ui
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>touch事件</title> <style> .body{ margin: 0; padding: 0; } .box{ width: 200px; height: 200px;background: #ccc; float: left; } </style> </head> <body> <div class="box"></div> <script> window.onload=function(){ var box=document.querySelector('.box'); box.addEventListener('touchstart',function(e){ console.log('開始座標('+e.touches[0].clientX+','+e.touches[0].clientY+')'); }); box.addEventListener('touchmove',function(e){ console.log('移動的座標('+e.touches[0].clientX+','+e.touches[0].clientY+')'); }); box.addEventListener('touchend',function(e){ console.log('結束的座標不會記錄'); }); } </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>手勢事件的實現</title> <style> .body{ margin: 0; padding: 0; } .box{ width: 200px; height: 200px;background: #ccc; float: left; } </style> </head> <body> <div class="box"></div> <script> window.onload=function(){ // 封裝手勢的函數 var bindSwipeEvent=function(dom,rightCallback,leftCallback){ // 手勢實現的條件:滑動而且滑動距離大於50px var isMove=false; var startX=0; var distanceX=0; dom.addEventListener('touchstart',function(e){ startX=e.touches[0].clientX; }); dom.addEventListener('touchmove',function(e){ isMove=true; var moveX=e.touches[0].clientX; distanceX=moveX-startX; }); dom.addEventListener('touchend',function(e){ // 滑動結束 if(isMove && Math.abs(distanceX)>50){ if(distanceX>0){ rightCallback && rightCallback.call(this,e); }else{ leftCallback && leftCallback.call(this,e); } } // 重置參數 isMove=false; startX=0; distanceX=0; }); }; // 調用 bindSwipeEvent(document.querySelector('.box'),function(e){ console.log('左滑手勢'); },function(e){ console.log('右滑手勢'); }) } </script> </body> </html>