JavaScript - 检测按钮上的滑动?

时间:2017-09-06 18:53:32

标签: javascript mobile swipe

我有一个按钮,我想知道你是否可以(在移动平台上)允许用户按住并向上滑动按钮。这会导致调用函数:

按钮+(按钮向上滑动)==通话功能

移动浏览器是否可行。谢谢?!?

2 个答案:

答案 0 :(得分:1)

您可以使用此功能:

$(window).load(function(){
  detectswipe('btnid',myfunc);
});

function detectswipe(el,func) {
  swipe_det = new Object();
  swipe_det.sX = 0; swipe_det.sY = 0; swipe_det.eX = 0; swipe_det.eY = 0;
var min_x = 100;    //min x swipe for horizontal swipe
var max_x = 100;    //max x difference for vertical swipe
var min_y = 100;    //min y swipe for vertical swipe
var max_y = 100;    //max y difference for horizontal swipe
var direc = "";
ele = document.getElementById(el);
if(ele==null){
    return;
}
ele.addEventListener('touchstart',function(e){
    var t = e.touches[0];
    swipe_det.sX = t.screenX;
    swipe_det.sY = t.screenY;
},false);
ele.addEventListener('touchmove',function(e){
    var t = e.touches[0];
    swipe_det.eX = t.screenX;
    swipe_det.eY = t.screenY;
},false);
ele.addEventListener('touchend',function(e){
    if ((((swipe_det.eX - min_x > swipe_det.sX) || (swipe_det.eX + min_x < swipe_det.sX)) && ((swipe_det.eY < swipe_det.sY + max_y) && (swipe_det.sY > swipe_det.eY - max_y) && (swipe_det.eX > 0)))) {
        if(swipe_det.eX > swipe_det.sX) direc = "right";
        else direc = "left";
    }
    else if ((((swipe_det.eY - min_y > swipe_det.sY) || (swipe_det.eY + min_y < swipe_det.sY)) && ((swipe_det.eX < swipe_det.sX + max_x) && (swipe_det.sX > swipe_det.eX - max_x) && (swipe_det.eY > 0)))) {
        if(swipe_det.eY > swipe_det.sY) direc = "down";
        else direc = "up";
    }
    if (direc != "") {
        if(typeof func == 'function') func(el,direc);
    }
    direc = "";
    swipe_det.sX = 0; swipe_det.sY = 0; swipe_det.eX = 0; swipe_det.eY = 0;
},false);
}

function myfunc(el,d){
 if(d=="up"){
   console.log("do Some Work!!");//or any function which you want to call on swipe up/down(matter of prespective,change "up" to down if you want the other way).
 }
}

它通过touchevents检测滑动方向。 我在我的项目中使用了这个功能,它在所有触摸设备上运行得非常好:)

答案 1 :(得分:0)

我过去使用过Hammer.js取得了成功。你可以原生这样做,但我认为使用Hammer.js总体上更容易。

https://hammerjs.github.io/