Home  >  Article  >  Web Front-end  >  JavaScript CSS Modification Learning Chapter 5 Adding Styles to "Upload"_Basic Knowledge

JavaScript CSS Modification Learning Chapter 5 Adding Styles to "Upload"_Basic Knowledge

WBOY
WBOYOriginal
2016-05-16 18:34:091125browse

Problem
In a website, my input box may look like this:
image
The designer may want the upload part to look like this and then add a select button. But when I want to change the normal input box to an upload box it doesn't work at all. Browsers vary greatly, and styling the default buttons is nearly impossible.
image

This is hardly a well-designed upload box, but it’s the best we can do.

Notice that Safari’s design is a little different. The Safari team wants to turn off the function of manually inputting files, and may be worried about such overflow. One disadvantage of this design is that users cannot cancel uploading a file after selecting it.

Solution

ReaderMichael McGrady invented a nice little trick to solve the problem of styling the upload button. All the solutions on this page were invented by him, I just added position:relative, some comments and tests, and then converted to JavaScript.

When not using this technique:

After using it, I want to be like this:

image

Looking better now, don’t you?

McGrady’s method is simple and elegant:

1. Set a normal <font face="NSimsun"><input type="file"></font> and place it in an element containing the postion:relative attribute.

2. Also in the parent element, add a normal and an image, and set styles for them. Set the absolute position for it so that this ordinary input can overlap with .

3. Then set the z-index of to 2, so that it can be displayed on ordinary input.

4. Finally, set the opacity of to 0. In this way, will be invisible, and the input/image below will be displayed, but you can still click the "Browse" button. If the button is positioned above the image, it will appear as if the image was clicked.

Note that you cannot use visibility:hidden, because a truly invisible element is not clickable, we need an invisible element that is clickable.

At this point, this effect can be displayed through pure CSS, but it is still a little short of

5. When the user selects a file, the visible fake input box should display the path of the selected file, just like the normal . Although you only need to simply copy the content of , JavaScript is still required.

So this technology may not be fully implemented without JavaScript. I'll explain why in a moment. I decided to write the whole idea in JavaScript. If you want to use an upload box without displaying the file name, you can also use pure CSS, although this is not a good idea.

HTML/CSS structure
I plan to use the following HTML/CSS structure:

Copy code The code is as follows:

div.fileinputs {
position: relative;
}

div.fakefile {
position: absolute;
top: 0px;
left: 0px;
z-index: 1;
}

input.file {
position: relative;
text-align: right;
-moz-opacity:0 ;
filter:alpha(opacity: 0);
opacity: 0;
z-index: 2;
}


                                                                                                                      .gif" /> Place an absolute position layer inside: the fake input box.

contains a fake input box and a button. Its position is absolute and its z-index value is 1, so that it can be under the real upload box. show.

The real upload box also has a position attribute relavtive, so that its z-index value can be set. In short, the upload box needs to be displayed above the fake input box. Then we set its transparency to 0 to make it invisible.

You also need to pay attention to text-align:right: Because Mozilla cannot set the width of the upload box, we need to ensure that the browse button is on the right edge of the DIV. The fake button should also be on the right, and should be below the real one. .

You will also need some css code to set the width height borders etc., which I did not write in this example.


Why JavaScript?
The first reason to use JavaScript is to copy the file path into the fake text box.

Second, JavaScript will ignore meaningless HTML code:
, keeping the code clean.

Finally, for some old browsers that cannot handle CSS, file input in Netscape and IE4 is inaccessible. For those browsers without CSS, users will see two input boxes and not understand what the second one is for.



Problems with Netscape 4

In Netscape 4, users can only see buttons. Maybe it's because of position:absolute.



Problems with IE4

In IE4, there is a weird shadow of the original "Browse" button, and it cannot be clicked. There is no solution

image

Netscape 3 problem

For those browsers without CSS capabilities. Although it works, the two input boxes will make users frustrated.

image

Solution-JavaScript

The solution to these problems is JavaScript: generate input boxes and buttons through JavaScript. The worst case scenario now is that the JavaScript cannot be executed, and even then, the user can still upload the file. It's not that pretty, but it still works.

So the original complex HTML becomes: image

Copy code

The code is as follows:

We add other elements through JavaScript.
Code




Copy code


The code is as follows:

var W3CDOM = (document.createElement && document.getElementsByTagName);
function initFileUploads() {
    if (!W3CDOM) return;
    var fakeFileUpload = document.createElement('div');
    fakeFileUpload.className = 'fakefile';
    fakeFileUpload.appendChild(document.createElement('input'));
    var image = document.createElement('img');
    image.src='pix/button_select.gif';
    fakeFileUpload.appendChild(image);
    var x = document.getElementsByTagName('input');
    for (var i=0;i        if (x[i].type != 'file') continue;
        if (x[i].parentNode.className != 'fileinputs') continue;
        x[i].className = 'file hidden';
        var clone = fakeFileUpload.cloneNode(true);
        x[i].parentNode.appendChild(clone);
        x[i].relatedElement = clone.getElementsByTagName('input')[0];
        x[i].onchange = x[i].onmouseout = function () {
            this.relatedElement.value = this.value;
        }
    }
}

解释
如果浏览器不支持W3C DOM,那么什么也不做。
复制代码 代码如下:

var W3CDOM = (document.createElement && document.getElementsByTagName);
function initFileUploads() {
    if (!W3CDOM) return;

创建
和他的内容。需要的时候我们会复制它。
复制代码 代码如下:

var fakeFileUpload = document.createElement('div');
fakeFileUpload.className = 'fakefile';
fakeFileUpload.appendChild(document.createElement('input'));
var image = document.createElement('img');
image.src='pix/button_select.gif';
fakeFileUpload.appendChild(image);

然后遍历页面上的所有input,如果不是则忽略。
复制代码 代码如下:

var x = document.getElementsByTagName('input');
for (var i=0;i    if (x[i].type != 'file') continue;

再做一次检测:如果的父元素没有fileinputs的class,则忽略。
复制代码 代码如下:
if (x[i].parentNode.className != 'fileinputs') continue;

现在我们就找到了需要添加样式的上传框。首先我们添加一个hidden的类名。
复制代码 代码如下:
x[i].className = 'file hidden';

复制假的输入框然后添加在的父元素上。
复制代码 代码如下:
var clone = fakeFileUpload.cloneNode(true);
x[i].parentNode.appendChild(clone);

现在我们就成功的添加了样式。但是还没有结束,我们希望用户在输入框内看到文件路径。
首先我们给创建一个属性,指向假的输入框:
复制代码 代码如下:
x[i].relatedElement = clone.getElementsByTagName('input')[0];

In this way, when the user changes the uploaded file, we can easily and promptly access the fake input box and copy the path.
There is a question here, what event do we use? Usually the change event is used. When the uploaded file changes, the value of the fake input box also changes.
But Mozilla 1.6 does not support this event on the upload box (Firefox supports it). So I add an onmouseout event here. (It can also run under IE, but not Safari)
Copy the code The code is as follows:
x[i]. onchange = x[i].onmouseout = function () {
this.relatedElement.value = this.value; 3 }

Questions and Extensions
There is also a question where the user selects a The file cannot be canceled afterward.
Suppose that after the user selects a file, he suddenly does not want to upload it. Usually just deleting the file path is enough. But in our case it's difficult, give it a try, it's possible to delete but it's usually the opposite of what it feels like.
So we hope that users can also modify the real upload path by modifying the fake input box.
Allow selection is possible. When the user selects any part of the uploaded file, we select the entire contents of the fake input box.
[code] x[i].onselect = function () { 2 this.relatedElement.select(); 3 }
But the security of JavaScript does not allow the program to modify the upload path, so we cannot let the user modify it Enter the contents of the box to modify the real upload path. So I decided to abandon the onselect event.
A possible way is to add a clear button to the fake input box, and when the user clicks it, delete the original upload box and create a new one. This is clunky, but it does remove file paths that the user doesn't want to upload. I don't think this will work, and I didn't write this part of the code.
The path of the click event
Some readers suggested to remove the complicated CSS, completely hide the upload box, and then bind the click event of the fake input box to the real upload box. Great idea, and much simpler than the above.
[code] fakeField.onclick = function () { 2 realField.click() 3 }
This click() method allows you to simulate a form item. Checkboxes are clicked, radio boxes are selected, etc. However, Mozilla and Opera do not support it. I want to know why, because the biggest insecurity of adding this method is that a dialog box for selecting files pops up.
So we can’t use this simple method.
Translation address: http://www.quirksmode.org/dom/inputfile.html
Please keep the following information for reprinting
Author: Beiyu (tw:@rehawk)
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn