简体   繁体   English

使用jQuery,HTML和CSS创建自定义文件上传

[英]Creating a custom file upload with jQuery, HTML and CSS

I have this small problem with a website I'm designing. 我要设计的网站有这个小问题。 It's fairly over, but I think the jQuery is the problem here. 它已经结束了,但是我认为jQuery是这里的问题。

The code is as follows: 代码如下:

<img src="files/register_page/upload_photo/body.png" id="upload">
<input type="file" name="file_upload" id="file_upload" style="visibility:hidden;">

And the jQuery is the following, in the part of the document: 在文档的一部分中,jQuery如下所示:

$(document).ready( function(){
      $("#upload").click( function(){
          $('#file_upload').click();
      });
    });

However, upon clicking the img, nothing happens, where a file upload dialog should pop up. 但是,单击img后,没有任何反应,应该会弹出一个文件上传对话框。 Please, if you need any more information or something, let me know. 请,如果您需要更多信息或其他信息,请告诉我。 If not, what could the problem be here? 如果没有,问题可能出在哪里? I'm using jQuery 1.8.0. 我正在使用jQuery 1.8.0。

Using HTML5 label element: 使用HTML5 标签元素:

<label for="file_upload"><img src="files/register_page/upload_photo/body.png" id="upload"></label>
<input type="file" name="file_upload" id="file_upload" style="visibility:hidden;">

Fiddle 小提琴

Works in Chrome, IE and Opera but not FF. 适用于Chrome,IE和Opera,但不适用于FF。

Browsers tend to limit what you can do with input type="file" . 浏览器倾向于限制您可以使用input type="file" The label element redirects the focus to the input with the id property equal to its for property, so this is an workaround to trigger the invisible element. label元素将焦点重定向到id属性等于其for属性的输入,因此这是触发不可见元素的一种解决方法。


Modern browsers have alleviated a good part of those restrictions though, so you can trigger the .click() without problem. 但是,现代的浏览器已经缓解了这些限制的大部分,因此您可以毫无问题地触发.click()

You may however, change the CSS hack to hide it without using display:none or visibility:hidden for back-compat with older browsers. 但是,您可以更改CSS hack使其隐藏,而无需使用display:nonevisibility:hidden来与旧版浏览器反向兼容。 Either

position:absolute; top:-100px;

Or 要么

opacity:0;
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
filter: alpha(opacity=0);
width:0; height:0;

Can hide the element without using the display or visibility CSS properties. 可以隐藏元素,而无需使用displayvisibility CSS属性。

Fiddle 小提琴


Also, here's an workaround for the label element on FF, you can change the visibility:hidden by opacity:0 and: 另外,这是FF上的label元素的一种解决方法,您可以更改opacity:0 visibility:hiddenvisibility:hidden

$('#file_upload').focus(function() {
    $(this).click();
});

Fiddle . 小提琴 But this should be unnecessary if the primary script works fine. 但是,如果主脚本运行正常,则这应该是不必要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM