如何在不触发focus事件的情况下让input元素获得焦点?
如何让input元素获得焦点但不触发focus事件?
你提供的示例代码运行后,调用elm.focus()会触发绑定的focus事件,但如果需要让元素获得焦点却不触发该事件,是可以实现的,以下是两种实用方案:
原问题触发事件的示例代码
JavaScript代码:
const elm = document.getElementById('fname'); elm.addEventListener('focus', evt => console.log( `input element focused, event.type: "${ evt.type }"` ) ); elm.focus(); // 这里会触发focus事件
HTML代码:
<input type="text" id="fname" name="fname">
方案一:临时移除后重新绑定事件监听器
核心思路是在调用focus()前先移除focus事件的监听器,获取焦点后再重新绑定,这样代码触发的焦点操作就不会触发事件逻辑:
const elm = document.getElementById('fname'); // 把事件处理函数单独提取,方便后续移除和绑定 const focusHandler = evt => console.log( `input element focused, event.type: "${ evt.type }"` ); elm.addEventListener('focus', focusHandler); // 临时移除监听器 elm.removeEventListener('focus', focusHandler); // 执行焦点操作,此时不会触发事件 elm.focus(); // 重新绑定监听器,不影响后续用户交互触发的事件 elm.addEventListener('focus', focusHandler);
方案二:通过event.isTrusted区分触发来源
如果你不需要移除监听器,只是想忽略**代码调用focus()**产生的事件,可以在事件处理函数中判断evt.isTrusted属性——该属性为true时表示事件是用户交互(比如点击、Tab切换)触发的,false则是脚本触发的:
const elm = document.getElementById('fname'); elm.addEventListener('focus', evt => { // 仅响应用户交互触发的focus事件 if (evt.isTrusted) { console.log( `input element focused, event.type: "${ evt.type }"` ); } }); // 代码调用focus,此时evt.isTrusted为false,不会执行日志输出 elm.focus();
注意:
isTrusted是浏览器原生支持的属性,兼容性良好,除了IE11及更早版本外,现代浏览器都支持。
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

