Join the AMA (Ask Me Anything) with the Firefox leadership team to celebrate Firefox 20th anniversary and discuss Firefox’s future on Mozilla Connect. Mark your calendar on Thursday, November 14, 18:00 - 20:00 UTC!

搜索 | 用户支持

防范以用户支持为名的诈骗。我们绝对不会要求您拨打电话或发送短信,及提供任何个人信息。请使用“举报滥用”选项报告涉及违规的行为。

详细了解

Why does https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/autofocus not work?

more options

In https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/autofocus, the browser compatibility box says that autofocus is supported by Firefox, Safari and Chrome. But when I use it, it only works in Chrome. I understand that this problem can easily be solved by .focus() but I just feel that the documentation is misleading.

In https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/autofocus, the browser compatibility box says that autofocus is supported by Firefox, Safari and Chrome. But when I use it, it only works in Chrome. I understand that this problem can easily be solved by .focus() but I just feel that the documentation is misleading.

所有回复 (3)

more options

Can you link to an example where it isn't working?

Here's a very simplified test case: https://www.jeffersonscher.com/res/autofocus-select.html

more options

I think I understand my problem. I didn't read the docs clearly enough. It is meant for "select" elements. I was using it on a text field. Here's an example of my code: document.getElementById("name").autofocus=true; It's selecting a text field with the Id of name. This works only in Chrome though.

more options

I don't think it's a problem with input vs. select. I think the MDN article says that Firefox only follows the autofocus attribute on page load. Setting it after page load in your script may well set the attribute, but that comes too late, Firefox ignores it at that point.

Perhaps if you are creating a new DOM element and you set the attribute before using appendChild or insertBefore to add the element to the page, then Firefox might follow it when it is added to the DOM. I haven't tested that.

But the traditional focus() method probably is what you need.