Tìm kiếm hỗ trợ

Tránh các lừa đảo về hỗ trợ. Chúng tôi sẽ không bao giờ yêu cầu bạn gọi hoặc nhắn tin đến số điện thoại hoặc chia sẻ thông tin cá nhân. Vui lòng báo cáo hoạt động đáng ngờ bằng cách sử dụng tùy chọn "Báo cáo lạm dụng".

Learn More

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.

Tất cả các câu trả lời (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.