這幾天做項目,發現移動端需要觸摸事件,而click肯定是不行的,於是我對tap事件封裝進行了搜索,找到了一篇文章,原文地址如下:http://www.jb51.net/article/50663.htm,
我對其中第一個封裝加了一點東西,把它封裝在一個函數里面,使用的時候直接調用即可,源代碼如下(tap.js):
function tap(ele, fn){ var startTx, startTy; var endTx, endTy; ele.addEventListener( 'touchstart', function( e ){ var touches = e.touches[0]; startTx = touches.clientX; startTy = touches.clientY; }, false ); ele.addEventListener( 'touchend', function( e ){ var touches = e.changedTouches[0]; endTx = touches.clientX; endTy = touches.clientY; if( Math.abs(startTx - endTx) < 6 && Math.abs(startTy - endTy) < 6 ){ fn(e); } }, false ); }
使用方法,引入js文件(即tap.js),然后執行如下調用:
/* 參數說明: ele:原生的dom對象 fn :回調方法,執行你需要的操作 */ tap(ele,function(e){ //你需要執行的操作 });