之前做手机端游戏的开发,遇到了需要点击事件、长按事件来触发‘上下左右’的场景,由于项目很急(好吧,其实是自己懒),网上直接搜索插件,痛快,不过提交测试悲剧了,ios非常正常,安卓就不行了,赶紧看了源码,我的天,看不懂,压缩的什么鬼(此处不贴图了)。
好吧,还是自己写吧,仔细回想了一下,自己的出发点有问题,点击事件用click事件,长按事件找插件,用类似于longPress之类的api。之后想起来touchstart、touchend
又上网简单查了一下用法,于是写了一个非常简单demo,点击或者长按按钮,数字累加,之后部署测试,发现还是不行,会有一些诡异的表现(其实就是微信浏览器默认行为),多方查找,请教朋友,总结出一些需要禁止的东西:
<style> body { -webkit-touch-callout: none !important; -webkit-overflow-scrolling: touch; } img,a{ pointer-events: none; } .long{ -webkit-user-select: none; } </style>
body里的东西,不用应该是可以去掉的(我项目需要),这里pointer-events:none;非常重要(因为上下左右肯定会有图的),.long不用多说,是我demo的button按钮,感兴趣的可以深入研究一下这些css,挺有趣的。
说了这么多废话,还是直接上代码吧,新需求来了,我要去搬砖了
<!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>长按</title> <style> body { -webkit-touch-callout: none !important; -webkit-overflow-scrolling: touch; } img,a{ pointer-events: none; } .long{ -webkit-user-select: none; } </style> <script src="jquery-3.0.0.min.js"></script> //当然也可以引入绝对路径 <body> <div style="margin-left: 200px;margin-top: 100px"><button class="long" style="width:100px;height:100px; user-select: none;"></button></div> <div style="margin-top: 100px;margin-left: 100px"><span id="num" style="font-size: 100px;">5</span></div> <script> <!--阻止默认行为,相当于鼠标右键--> window.document.oncontextmenu = function (e) { e.preventDefault(); }; var $long = $('.long'); var timer = null; $long.on('touchstart', function(){ plus('#num'); }); $long.on('touchend', function(){ clearTimeout(timer); }); function plus(ele){ var num = parseInt($(ele).text()); $(ele).text(++num); timer = setTimeout(function(){ plus(ele); }, 200); } </script>
</body> </html>总结:做完发现不难,就花了点时间做个记录,自己有时间也需要去深入学习css的一些原始的东西了,也希望有需要的小伙伴能省下一些时间,早点下班