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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM