js 触发长按事件
2023-09-14 08:58:44 时间
<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");
});
相关文章
- js 实现插入排序
- JS原生复制
- JS跳转代码_js中跳转页面路径
- 初识js中的闭包_Js闭包中变量理解
- 【说站】js中load事件如何理解
- JS获取当前年份_js获取当前时间年月日
- 初识vue.js模板语法
- 原生 JS 实现 HTML 转 Markdown ,html2md.js
- [javascript] 看知乎学习js事件触发过程详解编程语言
- PHP file_get_contents 读取js脚本的问题详解编程语言
- JS addEventListener()和attachEvent()方法:注册事件
- JS unload和beforeunload事件:页面卸载
- js鼠标、键盘事件实例代码
- js原生态函数中使用jQuery中的$(this)无效的解决方法
- 代码触发js事件(click、change)示例应用
- 浅析js设置控件的readonly与enabled属性问题
- js创建一个input数组并绑定click事件的方法
- 滚动条响应鼠标滑轮事件实现上下滚动的js代码
- JS实现OCX控件的事件响应示例