繁体   English   中英

Javascript:检测长按

[英]Javascript: Detecting a long press

为了区分触摸设备上的滚动和拖放,我决定考虑在长按之后发生拖动事件。

有没有办法使下面的代码更整洁?

const listItem = document.getElementById("listItem");
listItem.addEventListener("touchstart", onTouchstart);
listItem.addEventListener("touchmove", onTouchmove);
listItem.addEventListener("touchend", onTouchend);

const longpress = false;
const longpressStart = 0;
const longpressChecked = false;
const LONGPRESS_DURATION = 100;

function onTouchstart() {
    longpress = false;
    longpressStart = Date.now();
}

function isLongPress() {
    if (longpressChecked) {
        return longpress;
    }
    if (Date.now() - longpressStart >= LONGPRESS_DURATION) {
        longpress = true;
    }
    longpressChecked = true;
    return longpress;
}

function onTouchmove() {

    if (isLongPress()) {
        // drag and drop logic
    }
}

function onTouchend() {
    longpress = false;
    longpressStart = 0;
    longpressChecked = false;
}

谢谢你的帮助

您可以使用一些咖喱箭功能来美化它:

const listen (el, name) => handler => el.addEventListener(name, handler);

const since = (onStart, onEnd) => {
  let last = 0;
  onStart(() => last = Date.now());
  onEnd(() => last = 0);
  return time => Date.now() - last < time;
};

因此,您可以执行以下操作:

const longPress = since(
   listen(listItem, "touchstart"),
   listen(listItem, "touchend")
);

listen(listItem, "touchmove")(evt => {
  if(longPress(100)) {
    //...
   }
});
const listItem = document.getElementById("listItem");

listItem.addEventListener("touchstart", onTouchstart);
listItem.addEventListener("touchmove", onTouchmove);
listItem.addEventListener("touchend", onTouchend);

var onlongtouch = false;

function onTouchstart() {
  timer = setTimeout(function() {
    onlongtouch = true;
  }, 100);
}

function onTouchmove() {
  if(onlongtouch) {
    // do something
  }
}

function onTouchend() {
  if (timer)
    clearTimeout(timer);
  onlongtouch = false; 
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM