如何使用 JavaScript 触发文本框的焦点事件?

13

如何使用JavaScript触发文本框的焦点事件?

例如,在jQuery中,我们可以使用$('#textBox').focus()来触发焦点事件。

同样地,在纯JavaScript中,我们有类似的触发功能吗?


触发onfocus事件,可以参考http://www.w3schools.com/jsref/event_onfocus.asp。 - John Powell
3个回答

20
我最后不得不摆弄了一下,找到了一个似乎在各种浏览器上都能正常工作的解决方案。
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"事件。
测试过的浏览器版本如下:
- Firefox 62 - Chrome 69 - Internet Explorer 11(是的,我知道,我们在工作中必须支持它) - Microsoft Edge 15
使用方法如下:
let foo = document.getElementById("foo");

triggerFocus(foo);

这是通用的,适用于任何可以接收焦点的元素。


更新 #1

jQuery的focus()函数不会触发原生的焦点处理程序。当我混合使用通过HTMLElement.addEventListener(...)附加的原生焦点处理程序和通过jQuery附加的焦点事件处理程序时,我遇到了一些问题。虽然jQuery.focus()会触发使用addEventListener()附加的处理程序,但dispatchEvent()函数不会触发通过$("...").focus(event => { ... })附加的事件处理程序。如果您使用这个解决方案,请记住这一点。


"root未定义" 什么是root? - beliha
@beliha:非常抱歉。我的代码中有一个打字错误,我已经更正了。应该是 element - Greg Burghardt
太棒了。这应该是被接受的答案,因为它是唯一有效的! - beliha
嘿,实际上,我觉得这个答案很好,但是在 Firefox 102 版本上出现了“Uncaught TypeError: element.dispatchEvent is not a function”错误。也许,我的错误是什么? - jis0324
@jis0324:element 变量需要是 HTMLElement 的实例(或其子类之一)。基本上,您只能在 HTML 标记上触发事件。如果 element.nodeNameundefined,则表示您没有支持事件的元素。 - Greg Burghardt
1
好的,元素是jQuery选择器,它是列表。我刚刚尝试了element[0],它可以工作。谢谢。 - jis0324

2

是的,可以使用element.focus()实现。

document.getElementById("textBox").focus();

function myFunction(x) {
  x.style.background = "yellow";
} 
function focusText() {
document.getElementById("textBox").focus();
} 
Enter your name: <input type="text" id="textBox" onfocus="myFunction(this)">

<p>When the input field gets focus, a function is triggered which changes the background-color.</p>
<button onclick="focusText()">Focus the Textbox</button>


这也不会触发焦点事件。 - Greg Burghardt
以上的代码片段是否没有触发文本框的onfocus监听器myFunction() - Ankit Chaudhary
本地的 focus 函数将焦点设置到元素,但不会触发焦点或 focusin 事件。想象一下,如果 onfocus 再次将焦点设置在同一元素上,这将触发焦点事件,执行 onfocus,再次触发焦点事件... 这很容易创建一个递归函数调用。 - Greg Burghardt

-1

@Fahmi 我也是这么想的! - karns
2
我认为我知道原因:Element.focus()不会触发onfocus事件,至少在我的测试中是这样的。Greg建议使用dispatchEvent方法。 - Ruben Martinez Jr.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接