input file上傳文件改變默認樣式
- 2019 年 11 月 27 日
- 筆記
我們知道,在使用到input file上傳文件的時候,會出現這樣很醜的默認樣式,作為前端開發的我們,主要責任就是去優化這些樣式,以更美觀的方式呈現出來,但是,這個默認樣式沒有可以去修改的屬性,還是比較麻煩的。
這個時候,就需要用到一些障眼法了,將原來的樣式隱藏起來,再重新寫一個按鈕代替,與原來的位置重合即可。
原本的樣式是這樣的:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <input type="file" class="file-upload" /> </body> </html> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script> <script> </script>

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title></title> <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script> <style> #importExcel { color: #fff; width: 51px; height: 30px; display: inline-block; border: none; background: cornflowerblue; background-size: 100% 100%; } .change { position: absolute; display: block; width: 103px; top: 2px; left: 5px; height: 40px; opacity: 0; cursor: pointer; } .file-name { position: absolute; top: 9px; width: 133px; height: 30px; padding: 0 8px; line-height: 25px; margin-left: 86px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; cursor: pointer; } .btnMask { color: #fff; width: 86px; height: 30px; text-align: center; line-height: 30px; margin-right: 131px; display: inline-block; border: none; background: cornflowerblue; background-size: 100% 100%; cursor: pointer; } </style> </head> <body> <form s action="/criminal/import" id="uploadForm" enctype="multipart/form-data" method="post"> <a class="btnMask">選擇文件</a> <input class="change" id="mFile" type="file" name="mFile"> <div class="file-name"></div> <input type="button" value="導入" id="importExcel" name="btn"> </form> </body> <script> $("#mFile").change(function() { var arrs = $(this).val().split('\'); var filename = arrs[arrs.length - 1]; $(".file-name").html(filename); }); //導入按鈕 $('#importExcel').click(function() { if(checkData()) { $('#uploadForm').ajaxSubmit({ url: "http://localhost:3000/users", success: function(data) { alert(JSON.stringify(data)) for(var i = 0; i < data.length; i++) { // 這裡的i是代表數組的下標 if(i == data.length - 1) alert("已插入" + data[i] + "條罪犯數據") else alert(data[i]) } } }); } }); //JS校驗form表單資訊 function checkData() { var fileDir = $("#mFile").val(); var suffix = fileDir.substr(fileDir.lastIndexOf(".")); if("" == fileDir) { msg(5, "選擇需要導入的Excel文件!"); return false; } if(".xls" != suffix && ".xlsx" != suffix) { msg(5, "選擇Excel格式的文件導入!"); return false; } return true; } </script> </html>

這是改完以後的樣式,根據需要來設置屬性,這裡已經寫好了選擇文件,導入到表格裡面的效果啦。
原文作者:祈澈姑娘 技術部落格:https://www.jianshu.com/u/05f416aefbe1