如何判断函数是由blur或focus事件触发调用?含代码场景咨询
如何判断函数是由blur还是focus事件触发的?
嘿,这个问题其实挺实用的,我来一步步给你讲清楚~
一、通用判断方法:利用事件对象的type属性
当浏览器触发事件并调用回调函数时,会自动把事件对象(Event)作为参数传给回调。这个事件对象里的type属性就记录了当前触发的事件类型,比如'blur'或者'focus'。
1. 现代事件绑定(addEventListener)
这种方式下,事件对象会直接作为第一个参数传入函数:
function checkTriggerEvent(e) { if (e.type === 'blur') { console.log('当前是blur事件触发的函数'); } else if (e.type === 'focus') { console.log('当前是focus事件触发的函数'); } } // 给输入框绑定两个事件 const input = document.querySelector('#myInput'); input.addEventListener('blur', checkTriggerEvent); input.addEventListener('focus', checkTriggerEvent);
2. 旧版DOM0级绑定(onblur/onfocus)
如果是用element.onblur = 函数这种旧写法,要注意兼容IE的事件对象(IE里事件对象在window.event上):
function checkTriggerEvent() { // 兼容获取事件对象 const event = window.event || arguments[0]; if (event.type === 'blur') { // 处理blur相关逻辑 } else if (event.type === 'focus') { // 处理focus相关逻辑 } } const input = document.querySelector('#myInput'); input.onblur = checkTriggerEvent; input.onfocus = checkTriggerEvent;
二、针对指定代码中的my_func判断方法
核心思路还是让my_func能拿到事件对象,分两种情况:
1. my_func直接作为事件回调绑定
如果你的代码是直接把my_func绑定到blur/focus事件上,那直接在my_func里获取事件对象就行:
function my_func(e) { // 兼容获取事件对象 const event = e || window.event; if (event.type === 'blur') { console.log('my_func是被blur事件触发的'); } else if (event.type === 'focus') { console.log('my_func是被focus事件触发的'); } } // 假设绑定方式如下 const targetElement = document.querySelector('#target'); targetElement.addEventListener('blur', my_func); targetElement.addEventListener('focus', my_func);
2. my_func被其他函数间接调用
如果my_func是被一个包装函数调用的,那需要手动把事件对象传递给my_func:
// 包装函数,负责传递事件对象 function eventWrapper(e) { my_func(e); } function my_func(event) { if (event.type === 'blur' || event.type === 'focus') { console.log(`触发my_func的事件类型是:${event.type}`); } } // 绑定包装函数到事件上 const targetElement = document.querySelector('#target'); targetElement.addEventListener('blur', eventWrapper); targetElement.addEventListener('focus', eventWrapper);
内容的提问来源于stack exchange,提问作者Danny Beckett
相关产品推荐
相关产品推荐

