When using CSS to beautify form elements, there has never been a good way to beautify the file upload control. http://www.quirksmode.org/dom/inputfile.html (the website seems to have an error) provides a method to beautify the file upload control. Inspired by this method, I combined my own projects to improve its functions. After improvements, it has the following characteristics:
I encapsulated it into a jQuery plug-in. Since there is already a plug-in called jQuery.fakeFile on the Internet, in order to distinguish it, I will name it jQuery.liveFakeFile. This article will introduce the principle and use of this method.
1. Demand
The requirement is very simple, but its implementation requires certain skills, which are briefly described as follows:
2. Analysis
Realize the effect of popping up the picture selection dialog box by clicking the button
There is an input box in front of the text upload control. Inspired by Michael McGrady ( ljzcome once translated this article), we create an "upload image" button, then change the opacity property of the file upload control, set it to 0, and use the positioning property to make it The click area is above the button. In this way, every click by the user seems to be a clicked button, but in fact it is the text upload control itself.
Display user-selected images
Displaying pictures seems very simple, but there are differences between browsers. IE6 cannot display pictures correctly, and IE7 can display them by using the filter AlphaImageLoder. Firefox cannot display images normally, but it has a method to display images—getAsDataURL(). Other browsers Opera and Safari cannot display images properly. Therefore, we use browser sniffing technology to process different browsers separately, and only let browsers that cannot display images normally display text.
Determine image format
You only need to pass the regular expression verification when the change event of the file upload control is triggered. Once the format requirements are met, the image or prompt text will be displayed, otherwise an error message will be displayed.
usability analysis
Because js is used to change the appearance of the file upload control, it must be ensured that users can upload images normally when js is disabled. So what we place in the html structure should be a normal file upload control.