Javascript 单击打开文件上传对话框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6292825/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:08:38  来源:igfitidea点击:

open file upload dialog on click

javascriptjqueryhtmlfile-upload

提问by Niraj Choubey

I have to open file upload dialog by clicking some other button i.e i am hiding file upload control(visibility:hidden) and on clicking of some other button i want to open that dialog. Below is the code which i am having:

我必须通过单击其他按钮打开文件上传对话框,即我隐藏文件上传控件(可见性:隐藏)并单击其他按钮我想打开该对话框。以下是我拥有的代码:

<input type="file" style="visibility: hidden;" />

Below is the javascript:

下面是javascript:

$('#button').click(function() {
    $('input[type=file]').click();
});

It is working fine in Firefox 4 and IE8 but in chrome12 it is not working i.e the dialog is not being opened. Any idea why?

它在 Firefox 4 和 IE8 中工作正常,但在 chrome12 中它不起作用,即没有打开对话框。知道为什么吗?

回答by Kna?is

Tested today the simple code given in the question and the situation has changed:

今天测试了问题中给出的简单代码,情况发生了变化:

  • IE9: works
  • Chrome23: works
  • Firefox15: works
  • IE9:有效
  • Chrome23:有效
  • Firefox15:有效

There is just one catch - on IE the .click() is a blocking operation while on other browsers it is not.

只有一个问题 - 在 IE 上 .click() 是一个阻塞操作,而在其他浏览器上则不是。

回答by circusbred

In your example, your file input did not have an id, yet you are trying to reference it with #input. This works for me:

在您的示例中,您的文件输入没有 ID,但您尝试使用 #input 引用它。这对我有用:

$('#button').click(function() {
    $('input[type=file]').click();
});

回答by gaRex

You should position input[file] just above your custom control. And then bind to it`s onclick.

您应该将 input[file] 放在自定义控件的正上方。然后绑定到它的 onclick。

Also make in it bigger font-size, as only this way you can increase it's height.

还要让它更大的字体大小,因为只有这样你才能增加它的高度。