input file类型自定义样式

为了让上传这种类型的输入看起来更加美观,但是由于其自身往往无法定义样式,所以我们经常用按钮来 “替代” 它,接下来讲讲其原理和实践过程。
原理:为了让input[type='file']看起来更像一个button,我们首先先采用绝对定位定义一个<a>标签,然后采用绝对定位在相同的位置定义一个和<a>大小完全相同的<input type='file'>,并把其透明度设置为0,最后再定义一个div显示上传的文件名即可。
在这里插入图片描述

<!doctype html>
<html>
<head>
<style>
    .blueButton{ /*蓝色按钮,绝对定位*/
        position: absolute;
        display: block;
        width: 100px;
        height: 40px;
        background-color: #00b3ee;
        color: #fff;
        text-decoration: none;
        text-align: center;
        font:normal normal normal 16px/40px 'Microsoft YaHei';
        cursor: pointer;
        border-radius: 4px;
    }
    .blueButton:hover {
        text-decoration: none;
    }
    .myFileUpload{ /*自定义上传,位置大小都和a完全一样,而且完全透明*/
        position: absolute;
        display: block;
        width: 100px;
        height: 40px;
        opacity: 0;
    }
    .show{/*显示上传文件夹名的Div*/
        position: absolute;
        top:40px;
        width: 100%;
        height: 30px;
        font:normal normal normal 14px/30px 'Microsoft YaHei';
    }
</style>
<script src="jquery-3.1.0.min.js"></script>
<title>file自定义上传</title>
</head>
<body>
    <a href='javascript:void(0);' class="blueButton">选择文件</a>
    <input type="file" class="myFileUpload" />
    <div class="show"></div>
</body>
</html>
<script>
$(document).ready(function(){
    $(".myFileUpload").change(function(){
        var arrs=$(this).val().split('\\');
        var filename=arrs[arrs.length-1];
        $(".show").html(filename);
    });
});
</script>