寫在最前面
HTML自帶的上傳檔案元件樣式較醜陋。通常需要自定義元件樣式。思路是把上傳元件透明化(隐藏), 然後再自定義一個酷炫元件,點選酷炫元件的時候去模拟點選事件:模拟點選隐藏的元件
簡易demo
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiI0NXYFhGd192UvwVe0lmdhJ3ZvwFM38CXlZHbvN3cpR2Lc1TPB10QGtWUCpEMJ9CXsxWam9CXwADNvwVZ6l2c052bm9CXUJDT1wkNhVzLcRnbvZ2Lc1zYINGN5wmYr50MZZXUYpVd1kmYr50MZV3YyI2cKJDT29GRjBjUIF2LcRHelR3LcJzLctmch1mclRXY39DM5ADM0IzM3EDMxATM3EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
code
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<style>
.fileClassDiv {
margin: px;
padding: px;
border: px solid #3089dc;
text-align: center;
font-size: px;
width: px;
}
.fileClassInput {
filter: alpha(opacity=);
opacity: ;
width: ;
height: ;
}
</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("\\") + );
videoDivElement.html(videoTip);
});
</script>
<body id="bodyId">
<div class="fileClassDiv">+</div>
<input class="fileClassInput" type="file"/>
</body>
</html>