zoukankan      html  css  js  c++  java
  • js 触发长按事件

    <button id="btn1">长按触发</button>
    <button id="btn2">长按触发2</button>
    
    interface IOpt {
      el: HTMLElement;
      listener: EventListener;
      options?: boolean | AddEventListenerOptions;
    }
    
    function createBingEvent(event: boolean, types: string[]) {
      return ({ el, listener, options }: IOpt): Promise<IOpt> => {
        return new Promise((res) => {
          if (!event) return res({ el, listener, options });
    
          let timer: number | null;
          const clearTimer = () => {
            if (timer) {
              clearTimeout(timer);
              timer = null;
            }
          };
    
          types.forEach((type, index) => {
            el.addEventListener(
              type,
              (e) => {
                if (index === 0) {
                  if (timer) clearTimer();
                  timer = window.setTimeout(() => listener.call(el, e), 500);
                } else {
                  clearTimer();
                }
              },
              options
            );
          });
        });
      };
    }
    
    const pointTypes = ["pointerdown", "pointerup", "pointercancel"];
    const touchTypes = ["touchstart", "touchend", "touchcancel"];
    const mouseTypes = ["mousedown", "mouseup"];
    const chainPointerEvent = createBingEvent(!!window.PointerEvent, pointTypes);
    const chainTouchEvent = createBingEvent(!!window.TouchEvent, touchTypes);
    const chainMouseEvent = createBingEvent(!!window.MouseEvent, mouseTypes);
    
    export function bindLongEvent(
      el: HTMLElement,
      listener: EventListener,
      options?: boolean | AddEventListenerOptions
    ) {
      Promise.resolve({ el, listener, options })
        .then(chainPointerEvent)
        .then(chainTouchEvent)
        .then(chainMouseEvent);
    }
    
    bindLongEvent(document.getElementById("btn1")!, function (this: any, e) {
      console.log(this);
      console.log(e.type);
      console.log("触发长按事件");
    });
    bindLongEvent(document.getElementById("btn2")!, function (this: any, e) {
      console.log(this);
      console.log("hello world");
    });
    
  • 相关阅读:
    1.12学习总结:分区
    1.11学习总结:持久化
    1.10学习总结:RDD的行动操作
    1.9学习总结:RDD的转换操作
    1.8学习总结:RDD创建
    1.7学习总结:pyspark实例WordCount
    1.6学习总结:Spark集群的高可用配置
    1.5学习总结:安装Spark
    毕业设计第四周第七天完成情况汇总
    毕业设计第四周第五天完成情况汇总
  • 原文地址:https://www.cnblogs.com/ajanuw/p/12743024.html
Copyright © 2011-2022 走看看