①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>