移动端长按事件

xiaoxiao2021-02-28  120

主要用到兼容性还比较好的H5的touchstart、touchend事件

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> </head> <body> <div class="object" style="width:100px; height:100px; background:#ddd;">out</div> </body> </html> <script language="javascript" src="https://cdn.bootcss.com/jquery/1.12.0/jquery.js"></script> <script> $.fn.longPress = function(fn) { var timeout = undefined; var $this = this; for(var i = 0;i<$this.length;i++){ $this[i].addEventListener('touchstart', function(event) { timeout = setTimeout(fn, 800); //长按时间超过800ms,则执行传入的方法 }, false); $this[i].addEventListener('touchend', function(event) { clearTimeout(timeout); //长按时间少于800ms,不会执行传入的方法 }, false); } } $('.object').longPress(function(){ alert("移动端你长按啦!!!"); }); </script>
转载请注明原文地址: https://www.6miu.com/read-28164.html

最新回复(0)