分享一段自己用的元素长摁事件代码,非常好用支持安卓、IOS
var longPress = function(dom,time,callback){ try{ time = parseFloat(time)>1?parseFloat(time)*1000:1000; var elem =document.querySelector(dom); if(elem){ var startTime = 0,touch = false,ctime; elem.addEventListener("touchstart",function(e){ startTime = e.timeStamp touch = true; ctime = setInterval(function(){ startTime += 500; if( startTime>time && touch == true ){ typeof(callback) == 'function' && callback(); startTime = 0; touch = false; clearInterval(ctime); } },500); }); elem.addEventListener("touchend",function(e){ if((e.timeStamp - startTime)>time && touch == true ){ typeof(callback) == 'function' && callback(); startTime = 0; touch = false; } clearInterval(ctime); }); elem.addEventListener("touchmove",function(e){ touch = false; }); return elem; } }catch(err){ } return false; }
使用方法:
/** * @longPress * param1 # 元素【ID、类名、元素名】 * param2 # 长摁N秒执行回调 * param3 # 回调 * **/ longPress("body",2,function(){ // OK });
禁止任何人转载!