移動端長按圖片或者元素的時候會出現默認的瀏覽器事件,這樣會影響自定義的長按行為,很麻煩。微信的圖片和元素的長按事件效果如下
找到了一個方式去掉,參考https://segmentfault.com/q/1010000005088048
首先要把圖片放到div的背景圖片中(用圖片試了不行,如果有大神可以指點下),這樣再長按的時候長按的是DIV
代碼如下,注意引jQuery
//長按觸發事件 $.fn.longLongPress = function () { var div = $(this); $(this).on({ touchstart: function(e){ console.log('a') timeOutEvent = setTimeout(function(){ //阻止長按默認行為 $(div).bind('contextmenu', function(e) { e.preventDefault(); }) },200); }, touchmove: function(e){ clearTimeout(timeOutEvent); timeOutEvent = 0; }, touchend: function () { clearTimeout(timeOutEvent); if(timeOutEvent != 0){ console.log('這是點擊,不是長按'); } return false; } }) } $('div').longLongPress();//給div設置背景圖片並加上長按事件