同时支持长按和点击事件,无依赖版
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no"> <title>Document</title> </head> <style> body { max- 540px; min- 320px; } </style> <body> <button id="longPress">longPress</button> <li class="longPress">longPress</li> <li class="longPress">longPress</li> <li class="longPress">longPress</li> <li class="longPress">longPress</li> </body> <script> /** * 绑定长按事件,同时支持绑定点击事件 * @param {dom} dom 需要绑定的dom元素 * @param {fn} longPressCallBack 长按事件执行的方法 * @param {fn} touchCallBack 点击事件执行的方法 */ var longPress = function (dom, longPressCallBack, touchCallBack) { var timer = undefined; var isLongPress = false; var setEvent = function (e) { e.addEventListener('touchstart', function(event) { timer = setTimeout(function () { isLongPress = true longPressCallBack && longPressCallBack(e); }, 500); }, false); e.addEventListener('touchmove', function(event) { clearTimeout(timer); }, false); e.addEventListener('touchend', function(event) { if (!isLongPress) touchCallBack && touchCallBack() clearTimeout(timer); isLongPress = false; }, false); } if (dom.length) { // 支持绑定多个元素 for (var i = 0; i < dom.length; i++) { setEvent(dom[i]) } } else { setEvent(dom) } } longPress(document.getElementById('longPress'), function () { console.log('longPress') }, function () { console.log('touch'); }); [...document.querySelectorAll('.longPress')].forEach(function (e, i) { longPress(e, function () { console.log('longPress') }, function () { console.log('touch'); }); }); </script> </html>
jquery / zepto版本的实现,注意闭包的问题
$.fn.longPress = function(callback) { var timer = undefined; var $this = this; // 支持绑定多个元素 for (var i = 0; i < $this.length; i++) { var self = $this[i];
// 注意这里的闭包问题 (function(e){ self.addEventListener('touchstart', function(event) { timer = setTimeout(function () { callback(e); }, 500); }, false); self.addEventListener('touchmove', function(event) { clearTimeout(timer); }, false); self.addEventListener('touchend', function(event) { clearTimeout(timer); }, false); })($this[i]); } } // 调用示例 $(".card-con li").longPress(function(e){ console.log(e, $(e).index()); });
知乎上找到的原生实现:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title></title> <script type="text/javascript" src="http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js"></script> </head> <body> <div style="100%;"> <div id="touchArea" style="90%; height:200px; background-color:#CCC;font-size:100px">长按我</div> </div> <script> var timeOutEvent=0; $(function(){ $("#touchArea").on({ touchstart: function(e){ timeOutEvent = setTimeout("longPress()",500); e.preventDefault(); }, touchmove: function(){ clearTimeout(timeOutEvent); timeOutEvent = 0; }, touchend: function(){ clearTimeout(timeOutEvent); if(timeOutEvent!=0){ alert("你这是点击,不是长按"); } return false; } }) }); function longPress(){ timeOutEvent = 0; alert("长按事件触发发"); } </script> </body> </html>