Javascript focus on browse button of file input

 ̄綄美尐妖づ 提交于 2020-05-16 08:05:30

问题


I am trying to focus on the browse button of the file input control.

so I have something like

 <input type="file" name="upload" id="upload" >

and in javascript I have

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

but the focus remain on the text field and comes to browse button only after i hit tab. Is there a way that I could write a script to set the focus on the browse button?

Thanks for your help!


回答1:


Can't be done. You have almost zero control over the constituent parts of a file upload field, partly for security reasons and partly because the standards do not define what constituent parts a file upload field might have. It is entirely possible the browser might render a file upload interface without any ‘Browse’ button.




回答2:


This question's been around for a while, allowing standards to evolve and develop with new functionality, but I've had success with the following code:

<input type="file" id="file_field" />

<input type="button" value="click me"
    onclick="document.getElementById('file_field').click()" />

I've managed to test it in Chrome and Internet Explorer 7, 8 and 9 so far, and I suspect it would work in Firefox too. Hope this helps someone!



来源:https://stackoverflow.com/questions/1925811/javascript-focus-on-browse-button-of-file-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!