写在最前面
HTML自带的上传文件组件样式较丑陋。通常需要自定义组件样式。思路是把上传组件透明化(隐藏), 然后再自定义一个酷炫组件,点击酷炫组件的时候去模拟点击事件:模拟点击隐藏的组件
简易demo
code
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<style>
.fileClassDiv {
margin: 8px;
padding: 32px;
border: 1px solid #3089dc;
text-align: center;
font-size: 25px;
width: 232px;
}
.fileClassInput {
filter: alpha(opacity=0);
opacity: 0;
width: 0;
height: 0;
}
</style>
</head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$(function () {
// + 监听
$(document).on("click", ".fileClassDiv", function () {
console.log(this);
var fileInputElement = $(this).parent().children(".fileClassInput");
fileInputElement.trigger("click");
})
});
// 上传视频input监听
$(document).on("change", ".fileClassInput", function () {
// 视频名字
var videoDivElement = $(this).parent().children(".fileClassDiv");
// 视频名字回填div
videoTip = $(this).val().substring($(this).val().lastIndexOf("\\") + 1);
videoDivElement.html(videoTip);
});
</script>
<body id="bodyId">
<div class="fileClassDiv">+</div>
<input class="fileClassInput" type="file"/>
</body>
</html>