【问题标题】:Javascript: Detecting a long pressJavascript:检测长按
【发布时间】:2018-06-24 19:22:28
【问题描述】:

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

有没有办法让下面的代码更干净?

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;
}

感谢您的帮助

【问题讨论】:

    标签: javascript drag-and-drop touch long-press


    【解决方案1】:

    你可以通过使用一些柯里化的箭头函数来美化它:

    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 listen (el, name) => handler => el.addEventListener(name, handler);”缺少“=”
    【解决方案2】:
    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; 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-16
      • 2018-08-17
      • 2014-01-19
      • 1970-01-01
      相关资源
      最近更新 更多