文件上傳input簡便美化方案


文件上傳input在各個瀏覽器里表現形式都不一樣:

ie6

 

ie7,8,9

ff

chrome

這里介紹一種簡單實用的,在各種瀏覽器下表現一致的美化方法,效果如下:

ie6無法美化,只能應用部分效果,如下:

選擇文件后(以ff為例,不用瀏覽器顯示的路徑不同):

html代碼:

1  <form id="UploadForm" method="post" enctype="multipart/form-data">
2    <div class="file-uploader-wrap">
3      <input type="file" class="file-uploader"  name="uploadDataField" id="FileUploader"/>
4      <div class="file-uploader-wrap-fake">
5        <input type="text" id="PathDisplayer" class="input-text" disabled />
6        <a href="javascript:void(0)" class="link-btn" >選擇文件</a>
7      </div>
8    </div>
9  </form>

css代碼:

body{
    font-size: 12px;
    text-align: left;
}
.input-text{
    height: 23px;
    width: 315px;
    line-height: 23px;
    vertical-align: middle;
    background: #FAFBFD;
    border:1px solid #d4d4d4;
}
.link-btn{
    width: 78px;
    height: 25px;
    display: inline-block;
    line-height: 25px;
    text-align: center;
    vertical-align: middle;
    background: url('./images/btn.png') 0 -110px;
    color: #6d767f;
    text-decoration: none;
}
.file-uploader-wrap{
    position: relative;
    width: 405px;
    height: 27px;
    margin-top: 20px;
}
.file-uploader-wrap-fake{
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1;
    height: 27px;
    _display : none;
}
.file-uploader-wrap .file-uploader{
    position: relative;
    width: 400px;
    height: 27px;
    text-align: right;
    filter : alpha(opacity = 0);
    opacity: 0;
    z-index: 2;
    cursor: pointer;
    _filter : none;
    _text-align : left;
    _line-height : 27px;
}

js代碼:

 1 window.onload = function(){
 2     var fileUploader = document.getElementById('FileUploader');
 3     var pathDisplayer = document.getElementById('PathDisplayer');
 4     if(fileUploader.addEventListener){
 5         fileUploader.addEventListener('change', fileUploaderChangeHandler, false);
 6     }else if(fileUploader.attachEvent){
 7         fileUploader.attachEvent('onclick', fileUploaderClickHandler);
 8     }else{
 9         fileUploader.onchange = fileUploaderChangeHandler;
10     }
11 
12     function fileUploaderChangeHandler(){
13         pathDisplayer.value = fileUploader.value;
14     }
15     function fileUploaderClickHandler(){
16         setTimeout(function(){
17             fileUploaderChangeHandler();
18         }, 0);
19     }
20 }

在樣式方面,采用的是將上傳input設置為透明,並且置於文本框和選擇文件按鈕之上的方法。

.file-uploader中的text-align:right樣式是為了將file input置於右邊,從而使點擊選擇文件按鈕時可以點擊到file input。

js主要作用是選擇文件后將路徑顯示在文本框中。

  1. ie7,8只支持file input的click事件,在點擊file input時觸發,然后利用ie7,8中選擇文件對話框出現時會阻斷setTimeout的原理,在選擇文件后獲取file input的值。
  2. 由於ie6中文件選擇對話框並不能阻斷setTimeout,無法在選擇文件后及時獲取到文件路徑,所以無法對ie6進行美化。
  3. ie9既支持click事件,也支持change事件。
  4. ff和chrome只支持change事件,change事件在文件選擇之后觸發。

選擇文件后,就可以進行同步或者異步的文件上傳了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM