let timer: number | null;
const clearTimer = () => {
if (timer) {
clearTimeout(timer);
timer = null;
}
};
function createBingEvents({
el,
event,
types,
listener,
options,
}: {
el: HTMLElement;
event: boolean;
types: string[];
listener: EventListener;
options?: boolean | AddEventListenerOptions;
}) {
return new Promise((res, rej) => {
if (!event) return res();
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
);
});
});
}
function bindLongEvent(
el: HTMLElement,
listener: EventListener,
options?: boolean | AddEventListenerOptions
) {
createBingEvents({
event: !!window.PointerEvent,
types: ["pointerdown", "pointerup", "pointercancel"],
el,
listener,
options,
})
.then(() =>
createBingEvents({
event: !!window.TouchEvent,
types: ["touchstart", "touchend", "touchcancel"],
el,
listener,
options,
})
)
.then(() =>
createBingEvents({
event: !!window.TouchEvent,
types: ["mousedown", "mouseup"],
el,
listener,
options,
})
);
}
bindLongEvent(document.querySelector("button")!, function (this: any, e) {
console.log(this);
console.log(e.type);
console.log("触发长按事件.");
});