如何使用javascript触发文本框上的焦点事件?
例如,在 jQuery 中,我们可以使用以下命令触发焦点事件$('#textBox').focus()
.
同样,我们在纯 JavaScript 中是否有类似的触发器功能?
我最终不得不摆弄这个问题,并想出了一些似乎可以跨浏览器工作的东西:
function triggerFocus(element) {
let eventType = "onfocusin" in element ? "focusin" : "focus";
let bubbles = "onfocusin" in element;
let event;
if ("createEvent" in document) {
event = document.createEvent("Event");
event.initEvent(eventType, bubbles, true);
}
else if ("Event" in window) {
event = new Event(eventType, { bubbles: bubbles, cancelable: true });
}
element.focus();
element.dispatchEvent(event);
}
考虑到某些浏览器支持focusin
事件,有些只支持focus
事件。它使用本机设置焦点focus
函数,然后调度“focusin”事件或“focus”事件,具体取决于浏览器支持的事件。
测试于:
- 火狐62
- 铬69
- Internet Explorer 11(是的,是的。我知道。不过,我们必须在工作中支持它)
- 微软边缘15
并使用它:
let foo = document.getElementById("foo");
triggerFocus(foo);
这是通用的,应该适用于任何可以获得焦点的元素。
更新#1
jQueryfocus()
函数不会触发本机焦点处理程序。当混合通过附加的本机焦点处理程序时,我遇到了一些障碍HTMLElement.addEventListener(...)
并通过 jQuery 附加焦点事件处理程序。尽管jQuery.focus()
将触发使用附加的处理程序addEventListener()
, the dispatchEvent()
功能will not触发事件处理程序通过附加$("...").focus(event => { ... })
。如果您使用此解决方案,请记住这一点。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)