前端怎么修改input file的默认样式

如题所述

html文件:
<div class="fileBox">
<div class="fileName"></div>
<button class="fileButton">选择文件</button>
<input type="file" class="file1">
</div>
<div class="fileBox">
<div class="fileName"></div>
<button class="fileButton">选择文件</button>
<input type="file" class="file2">
</div>

css文件:
.fileBox{
position: relative;
display: inline-block;
}
.fileButton{
display: inline-block;
width: 80px;
height: 34px;
line-height: 34px;
background: #FFA837;
border-radius: 0px 4px 4px 0px;
text-align: center;
color: #fff;
vertical-align: top;
}
.file1,.file2{
width: 80px;
height: 34px;
position: absolute;
top: 0px;
right: 0px;
opacity: 0;
filter:Alpha(opacity=0); /*透明度兼容IE8*/
vertical-align: top;
}
.fileName{
display: inline-block;
width: 150px;
height: 34px;
line-height: 34px;
padding:0px 5px;
overflow: hidden;
text-overflow:ellipsis;
white-space: nowrap;
border: 1px solid #eee;
vertical-align: top;
float: left;
}

js文件:
function upFile(fileX){
var path;
var fileName;
var file=fileX;
var fileFrame=fileX.parent(".fileBox").children(".fileName");
path=file.val();

//path为获取的<input type="file">的文件名或文件路径
//火狐获取的是文件名,所以pos=-1,chrome和IE获取的是文件路径
if(path!=''){
var pos1 = path.lastIndexOf('/');
var pos2 = path.lastIndexOf('\\');
var pos = Math.max(pos1, pos2)
if( pos<0 ){
fileName =path;
fileFrame.text(fileName);
fileFrame.attr("title",fileName);
}
else{
fileName=path.substring(pos+1);//截取从pos+1索引到末尾
fileFrame.text(fileName);
fileFrame.attr("title",fileName);
}
}
}
调用:
$(".file1").change(function(){
upFile($(this));
});
$(".file2").change(function(){
upFile($(this));
});

以后只要调用upFile()就可以了
兼容:IE8+,firefox,chrome
温馨提示:答案为网友推荐,仅供参考
相似回答