h5移动端阻止浏览器长按事件

移动端长按图片或者元素的时候会出现默认的浏览器事件,这样会影响自定义的长按行为,很麻烦。微信的图片和元素的长按事件效果如下

找到了一个方式去掉,参考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设置背景图片并加上长按事件
原文地址:https://www.cnblogs.com/nightfallsad/p/7252396.html