1. 程式人生 > >input(file)樣式修改及上傳檔名顯示

input(file)樣式修改及上傳檔名顯示

實現思路:

  1. a標籤包裹input元素
  2. 設定a標籤為上傳按鈕的樣式,相對定位
  3. 設定input為透明,絕對定位,覆蓋到a上面

效果:看到的按鈕是a的樣式,點選時實際是點選input元素。樣式和功能都具備

html程式碼:

<a href="javascript:;" class="file">選擇檔案 
  <input type="file" >
</a>

CSS程式碼:

.file {
    position: relative;
    display: inline-block;
    border: 1px solid #333;
    padding: 4px 10px;
    overflow: hidden;
    text-decoration: none;
    text-indent: 0;
    line-height: 20px;
    border-radius: 5px;
    color: #000;
    background:#ccc; /* 一些不支援背景漸變的瀏覽器 */  
    background:-moz-linear-gradient(top, #fff, #ccc);  
    background:-webkit-gradient(linear, 0 0, 0 bottom, from(#fff), to(#ccc));  
    background:-o-linear-gradient(top, #fff, #ccc); 
}
.file input {    
    position: absolute;    
    font-size: 50px;    
    right: 0;    
    top: 0;    
    opacity: 0;
    filter: progid:DXImageTransform.Microsoft.Alpha(opacity=0);
}


效果:

此時上傳檔案的檔名不顯示,需要用js處理:

1 2 3 4 5 6 7 8 9 10 11 12 13 $(".file").on("change","input[type='file']",function(){ var filePath=$(this).val(); if(filePath.indexOf("jpg")!=-1 || filePath.indexOf("png")!=-1){ $(".fileerrorTip1").html("").hide(); var arr=filePath.split('\\');
var fileName=arr[arr.length-1]; $(".showFileName1").html(fileName); }else{ $(".showFileName1").html(""); $(".fileerrorTip1").html("您未上傳檔案,或者您上傳檔案型別有誤!").show(); return false } })

效果: