如何将输入按钮链接到文件选择窗口? [英] How to link an input button to a file select window?
问题描述
可能重复:
jQuery触发文件输入
我正在研究一种允许用户将图像上传到网站的表格.到目前为止,我有一个可在Chrome和Safari中运行的拖放解决方案.但是,我还需要支持用户单击按钮并以传统方式浏览文件的操作.
类似于此操作:
<input type="file" name="my_file">
但是,与其使用笨拙的文件描述区域和无法编辑的浏览"按钮,我不如使用以下内容:
<input type="button" id="get_file">
因此,我的问题是如何使此按钮打开文件选择窗口并以与type="file"
相同的方式处理选择?
干杯.
我的解决方案
HTML:
<input type="button" id="my-button" value="Select Files">
<input type="file" name="my_file" id="my-file">
CSS:
#my-file { visibility: hidden; }
jQuery:
$('#my-button').click(function(){
$('#my-file').click();
});
到目前为止,可以在Chrome,Firefox和IE7 +中使用(尚未尝试使用IE6).
单击按钮输入后,您可以使用JavaScript并触发隐藏文件输入.
http://jsfiddle.net/gregorypratt/dhyzV/-简单
http://jsfiddle.net/gregorypratt/dhyzV/1/-有点JQuery的爱好者>
或者,您可以直接在文件输入上设置div样式,并将CSS中的pointer-events
设置为none,以使单击事件传递到花式div后面的文件输入.不过,这仅在某些浏览器中有效; http://caniuse.com/pointer-events
Possible Duplicate:
Jquery trigger file input
I'm working on a form which allows users to upload images to a website. So far I have got a drag and drop solution working in Chrome and Safari. However I also need to support the action of users clicking a button and browsing for files in the traditional manner.
Similar to what this would do:
<input type="file" name="my_file">
However rather than having the clunky file description area and un-editable Browse button I would rather use something like this:
<input type="button" id="get_file">
My question therefore is how to I make this button open a file selection window and process the selection the same way that type="file"
would work?
Cheers.
My Solution
HTML:
<input type="button" id="my-button" value="Select Files">
<input type="file" name="my_file" id="my-file">
CSS:
#my-file { visibility: hidden; }
jQuery:
$('#my-button').click(function(){
$('#my-file').click();
});
Working in Chrome, Firefox, and IE7+ so far (haven't tried IE6).
You could use JavaScript and trigger the hidden file input when the button input has been clicked.
http://jsfiddle.net/gregorypratt/dhyzV/ - simple
http://jsfiddle.net/gregorypratt/dhyzV/1/ - fancier with a little JQuery
Or, you could style a div directly over the file input and set pointer-events
in CSS to none to allow the click events to pass through to the file input that is "behind" the fancy div. This only works in certain browsers though; http://caniuse.com/pointer-events
这篇关于如何将输入按钮链接到文件选择窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!