很多人在實際的開發中都會用到input type=file的這個標簽,然后就會開始吐槽,我的天,長這個樣怎么處理合適,今天給大家帶來一個原生改寫樣式的方法,希望能給大家帶來幫助
不帶任何改變的效果
這個原生真心丑
嘗試改變后的效果
簡單變樣之后
實現思路
先講講思路是如何,第一個就是用label標簽,將for指向上傳的type=file的input標簽,并且將input標簽給隱藏。
<!--multiple的屬性是可以支持多個內容一塊上傳-->
<input id="file" type="file" multiple>
<!--銅鼓label的指向,就可以用label替換input并且能夠有實現上傳功能-->
<label for="file">請選擇文件</label>
完整代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1, user-scalable=no">
<title>美化控件 & 獲取上傳文件的基本信息</title>
<style>
* {
margin: 0;
padding: 0;
}
h1 {
font-size: 2em;
font-weight: bolder;
color: red;
text-align: center;
}
fieldset {
width: 80%;
margin: 30px auto;
padding: 20px;
}
fieldset legend {
color: blue;
font-size: 1.3em;
font-weight: bold;
}
fieldset ul {
margin-left: 30px;
}
fieldset li {
line-height: 1.8;
color: #666;
}
.container {
width: 500px;
height: 300px;
margin: 20px auto;
padding: 10px;
border: 1px solid #888;
overflow: auto;
}
input[type=file] {
width: 0.1px;
height: 0.1px;
opacity: 0;
overflow: hidden;
position: absolute;
z-index: -1;
}
label[for=file] {
display: block;
width: 150px;
height: 40px;
margin: auto;
line-height: 40px;
text-align: center;
border-radius: 5px;
font-size: 1.25em;
font-weight: 700;
color: white;
background-color: #888;
transition: 0.5s;
}
label[for=file]:hover {
background-color: #666;
cursor: pointer;
}
pre {
font-size: 14px;
line-height: 1.4;
color: #333;
margin-top: 20px;
}
</style>
</head>
<body>
<h1>簡單的美化這個控件</h1>
<fieldset>
<legend>美化上傳文件表單控件</legend>
<ul>
<li>為控件綁定 label 標簽</li>
<li>隱藏這個丑陋的控件</li>
<li>美化綁定的 label 標簽</li>
</ul>
</fieldset>
<fieldset>
<legend>獲取上傳文件的基本信息</legend>
<ul>
<li>HTML5,為 input 添加 multiple 特性,允許上傳多個文件</li>
<li>綁定 input 的 change 事件,動態更改文件信息</li>
<li>獲取 FileList,HTMLInputElement.files</li>
<li>動態寫入文件信息(File 對象)</li>
</ul>
</fieldset>
<div class="container">
<div class="upload-file">
<input id="file" type="file" multiple>
<label for="file">請選擇文件</label>
<div class="file-info"></div>
</div>
</div>
<script>
let file = document.getElementById('file');
let fileInfo = document.getElementsByClassName('file-info')[0];
file.onchange = function() {
//.files是type-file的內置對象
let fileNum = file.files.length;
file.nextElementSibling.innerHTML = `選中 ${fileNum} 個文件`;
showFileInfo(fileNum);
};
function showFileInfo(num) {
let filelist = file.files;
let div = document.createElement('div');
for (let i = 0; i < num; i++) {
//pre就是可以保留計算機字符,不被解析
let pre = document.createElement('pre');
let item = filelist.item(i);
//字符串模板,類似于和拼接字符串相同效果,是es6的寫法
pre.innerHTML = `文件名:${item.name}\n文件大小:${item.size}(字節)\n文件類型:${item.type}\n文件最后修改日期:${(new Date(item.lastModified).toLocaleString())}\n`;
div.appendChild(pre);
}
fileInfo.innerHTML = '';
fileInfo.appendChild(div);
}
</script>
</body>
</html>