1. 程式人生 > >H5手機端iOS,安卓長按事件的解決方案

H5手機端iOS,安卓長按事件的解決方案

之前做手機端遊戲的開發,遇到了需要點選事件、長按事件來觸發‘上下左右’的場景,由於專案很急(好吧,其實是自己懶),網上直接搜尋外掛,痛快,不過提交測試悲劇了,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的一些原始的東西了,也希望有需要的小夥伴能省下一些時間,早點下班