實現思路:javascript
效果:看到的按鈕是a的樣式,點擊時實際是點擊input元素。樣式和功能都具有html
html代碼:java
<a href="javascript:;" class="file gradient">選擇文件
<input type="file" >
</a>
CSS代碼:web
.file { position: relative; display: inline-block; background: #ccc; border: 1px solid #333; padding: 4px 20px; overflow: hidden; text-decoration: none; text-indent: 0; line-height: 20px; border-radius: 20px; color: #333; font-size: 13px; } .file input { position: absolute; font-size: 100px; right: 0; top: 0; opacity: 0; }
.gradient{ filter:alpha(opacity=100 finishopacity=50 style=1 startx=0,starty=0,finishx=0,finishy=150) progid:DXImageTransform.Microsoft.gradient(startcolorstr=#fff,endcolorstr=#ccc,gradientType=0); -ms-filter:alpha(opacity=100 finishopacity=50 style=1 startx=0,starty=0,finishx=0,finishy=150) progid:DXImageTransform.Microsoft.gradient(startcolorstr=#fff,endcolorstr=#ccc,gradientType=0);/*IE8*/ 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); }
效果:瀏覽器
此時上傳文件的文件名不顯示,須要用js處理:ide
$(".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 } })
效果:this