javascript长按事件实现方式

先贴出实践中实现的代码,参考(https://segmentfault.com/q/1010000011640937?sort=created):

               parentObj.addEventListener("touchstart", function (e) {
                    console.log('touchstart');
                    timer = setTimeout(function () {
                        console.log('LongPress');
                        e.preventDefault();
                        LongPress(parentObj);
                    }, 800);
                });
                parentObj.addEventListener("touchmove", function (e) {
                    console.log('touchmove');
                    clearTimeout(timer);
                    timer = 0;
                });
                parentObj.addEventListener("touchend", function (e) {
                    console.log('touchend');
                    clearTimeout(timer);
                    //if (timer != 0) {
                    //    alert('这是点击,不是长按');
                    //}
                    return false;
                });

  

先获取元素对象,然后设置ontouchstart和ontouchend事件,注意,这里的是事件,和touchstart(方法)有所区别,然后在手机浏览器中,为了避免长按弹出窗口,设置e.preventDefafult()来屏蔽弹出。

 

其实,这些是比较容易,最常见的实现方式,在网上找资料的时候发现很多其他的实现,比如利用zepto.js插件,这是一个jQuery.js的移动端实现,通过这个库,实现方式如下:

,这个实现的链接(https://segmentfault.com/q/1010000003956296

自己也实现了,调试过程中,发现,在微信开发者工具里面,没有问题,longTap能调用,在手机上,就几乎调用不成功,触发的概率非常小,不知道是因为和手机上长按时有微小移动有关系。所以最终放弃了这个实现。

 

 

**********************************************分割线**********************************************

关于长按的弹窗菜单怎么屏蔽,网上查了很多资料,都是设置e.preventDefault(),来实现,但是一直用的是
//obj.addEventListener("touchstart", function (e) {
// e.preventDefault();
//}, false);
这个设置的应该是屏蔽触屏的反应,设置屏蔽弹出菜单的应该是这样:
document.oncontextmenu = function (e) {
e.preventDefault();
};

posted @ 2018-04-16 17:17  powerio  阅读(29031)  评论(1编辑  收藏  举报