web前端领域移动端自定义长按事件你用过吗?

一。在移动端开发过程中经常会用到长按事件,例如游戏中人物,长按上下左右会持续移动人物的位置,这是一个典型的长按事件的需求,但javaScript原生不支持长按事件,这就需要我们自定义一个长按事件以满足我们的需求。

1.由于移动端长按元素会触发许多默认行为,所以第一步我们要禁掉这些默认行为,css代码如下。

body {
   -webkit-touch-callout: none !important; /*当触摸并按住触摸目标时,禁止系统默认菜单。*/
}
 .long{
  -webkit-user-select: none;/*使文本元素不能被选择*/
}
2.移动端有原生触摸事件,touchstart:手指触摸屏幕,touchmove:手指在屏幕上滑动,touchend:手指离开屏幕;因此我的基本思路是,当手指触摸屏幕的目标元素时启用一个定时器在固定时间间隔内反复触发某行为,当手指离开屏幕时,清理定时器停止复发该行为。

3.具体操作案例如下:这里通过长按该按钮达到下面的数组持续增长的行为。代码如下:


<style>
        body {
            -webkit-touch-callout: none !important;
        }
        .long{
            -webkit-user-select: none;
        }
</style>
<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>
    var long = document.getElementsByClassName('long')[0];
    var timer = null;
    long.ontouchstart = function(){
        plus('#num');
    };
    long.ontouchend = function(){
        clearTimeout(timer);
    };
    function plus(ele){
        var targetEle = document.querySelector(ele);
        var num = parseInt(targetEle.innerText);
        console.log(targetEle.innerText);
        targetEle.innerText = ++num;
        timer = setTimeout(function(){
            plus(ele);
        }, 200);
    }
</script>





猜你喜欢

转载自blog.csdn.net/qq_19891827/article/details/79442913