在 JavaScript 中,我可以进行“点击"吗?以编程方式为文件输入元素触发事件?

2022-01-30 00:00:00 javascript html

我想以编程方式在 <input type="file"> 标记上触发点击事件.

I'd like to make a click event fire on an <input type="file"> tag programmatically.

只是调用 click() 似乎没有任何作用,或者至少它没有弹出文件选择对话框.

Just calling click() doesn't seem to do anything or at least it doesn't pop up a file selection dialog.

我一直在尝试使用侦听器捕获事件并重定向事件,但我无法让它像有人点击它那样实际执行事件.

I've been experimenting with capturing events using listeners and redirecting the event, but I haven't been able to get that to actually perform the event like someone clicked on it.

推荐答案

你不能在所有浏览器中都这样做,据说 IE 允许,但 Mozilla 和 Opera 不允许.

You cannot do that in all browsers, supposedly IE does allow it, but Mozilla and Opera do not.

当您在 GMail 中撰写邮件时,附加文件"功能在 IE 和任何支持此功能的浏览器中以一种方式实现,然后在 Firefox 和不支持此功能的浏览器中实现另一种方式.

When you compose a message in GMail, the 'attach files' feature is implemented one way for IE and any browser that supports this, and then implemented another way for Firefox and those browsers that do not.

我不知道你为什么不能这样做,但是是安全风险的一件事,你在任何浏览器中都不允许这样做,以编程方式设置文件名HTML 文件元素.

I don't know why you cannot do it, but one thing that is a security risk, and which you are not allowed to do in any browser, is programmatically set the file name on the HTML File element.

相关文章