如何动态获取WebAPI DOM事件及相关类型?构造器报错如何处理?
问题解答
1. 事件构造器与关联事件类型列表
以下是常见DOM事件构造器及其对应的事件类型:
- MouseEvent:click、dblclick、mousedown、mouseenter、mouseleave、mousemove、mouseout、mouseover、mouseup、contextmenu
- KeyboardEvent:keydown、keyup、keypress(部分浏览器已废弃)
- TouchEvent:touchstart、touchmove、touchend、touchcancel
- PointerEvent:pointerdown、pointermove、pointerup、pointercancel、pointerover、pointerout、pointerenter、pointerleave
- FocusEvent:focus、blur、focusin、focusout
- InputEvent:input、beforeinput
- UIEvent:resize、scroll、select
2. BeforeUnloadEvent 构造器错误解决
BeforeUnloadEvent 不能直接通过 new BeforeUnloadEvent() 实例化,这是浏览器的安全限制,直接调用会抛出“Illegal constructor”错误。正确的使用方式是通过事件监听触发:
- 使用
window.addEventListener监听beforeunload事件:window.addEventListener('beforeunload', (event) => { // 必须设置 returnValue 才能触发确认弹窗(部分浏览器忽略自定义文本) event.returnValue = '你确定要离开吗?'; // 同时返回字符串(兼容旧版浏览器) return '你确定要离开吗?'; }); - 或者使用
window.onbeforeunload赋值:window.onbeforeunload = function(event) { event.returnValue = '确认离开?'; return event.returnValue; };
注意:现代浏览器大多不会显示自定义提示文本,只会展示默认提示,但上述语法是符合规范的正确写法。
3. 动态关联事件类型与构造器的方案
正则映射的方式确实存在硬编码、依赖浏览器环境的问题,更动态的方案可以参考以下思路:
- 利用事件实例的 constructor 属性:对于支持直接实例化的事件构造器,创建实例后可通过
event.constructor关联,但像BeforeUnloadEvent这类受限制的事件无法直接创建实例。示例:const clickEvent = new MouseEvent('click'); console.log(clickEvent.constructor === MouseEvent); // true - 遍历全局对象检测事件构造器:通过遍历
window对象,筛选出以Event结尾的构造器,再通过尝试创建实例或查询文档来关联事件类型(需配合try-catch处理无法实例化的情况):const eventConstructors = Object.keys(window).filter(key => key.endsWith('Event')); eventConstructors.forEach(constructorName => { const Constructor = window[constructorName]; try { // 尝试创建空实例(部分事件需要必填参数) const event = new Constructor('test'); console.log(`${constructorName} 实例的构造器匹配成功`); } catch (e) { console.log(`${constructorName} 无法直接实例化`); } }); - 借助事件触发后的实例:在元素上触发一个事件,然后在事件回调中获取事件实例的构造器,以此建立映射。比如:
const div = document.createElement('div'); div.addEventListener('click', (e) => { console.log('click事件对应的构造器:', e.constructor); }); div.click();
内容的提问来源于stack exchange,提问作者user28534042
相关产品推荐
相关产品推荐

