兼容IE浏览器样式的html上传文件控件

时间:2023-03-09 00:14:02
兼容IE浏览器样式的html上传文件控件

最近在公司做项目时需要用到html的上传文件控件,但发现原生的上传文件控件<input type="file" />在IE、Chrome浏览器的显示效果相差很大,为了统一样式,我参考了网上的许多方法,下面给出我自己的代码实现(实际上就是在原生的input file上面加个外壳,再添加一些样式,让它看上去不像原生的这么丑)

html部分

<div class="upload-box">
<div class="input">
<input type="file" id="input" size="45"/> <!--原生的file-->
</div>
<div class="upload">
<div class="upload-choose">选择文件</div>
<div class="upload-info"></div>
</div>
</div>

css部分

 .upload-box {
position: relative;
} .input {
height: 30px;
position: absolute;
top: 0px;
left: 0px;
} input[type="file"] {
border: 1px solid red;
width: 480px;
opacity:;
} input[type="submit"] {
width: 100px;
height: 30px;
background: #ddd;
border: none;
} .upload-choose {
width: 80px;
height: 30px;
background: #eee;
float: left;
text-align: center;
line-height: 30px;
font-family: "Microsoft YaHei";
font-size: 14px;
font-weight: bold;
} .upload-info {
width: 400px;
border: 1px solid #eee;
height: 28px;
line-height: 28px;
float: left;
padding-left: 5px;
overflow: hidden;
}

js部分

 $(function(){
$("#input").change(function(){
var filename_split = $(this).val().split("\\");
var filename = filename_split[filename_split.length - 1];
$(".upload-info").text(filename);
});
});

这样基本上可以实现和原生上传控件相同的效果