长按触发(PC端和移动端)

$.fn.longPress = function(fn) {
                var timeout = undefined;
                var $this = this;
                for(var i = 0;i<$this.length;i++){
                    $this[i].addEventListener('touchstart', function(e) {
                        e.preventDefault();
                        timeout = setTimeout(fn, 800);
                        }, false);
                    $this[i].addEventListener('mousedown', function(e) {
                        e.preventDefault();
                        timeout = setTimeout(fn, 800);
                    }, false);
                    $this[i].addEventListener('touchend', function(e) {
                        e.preventDefault();
                        clearTimeout(timeout); 
                    }, false);
                    $this[i].addEventListener('mouseup', function(e) {
                        e.preventDefault();
                        clearTimeout(timeout);
                    }, false);
                }
            }
            $('button').longPress(function(){
                alert('长按')
            })

可用于多个元素

猜你喜欢

转载自www.cnblogs.com/yycc11/p/9087849.html