獲取input type=file的檔名及input type=file獲取檔名的瀏覽器,設定input type=file樣式
阿新 • • 發佈:2018-12-26
獲取input type=file的檔名方法:
let filePath = $("input[type = 'file']").val(); //獲取路徑
let urlArr = filePath.split("\\"); //以反斜槓'\'擷取檔名為陣列
let fileName = urlArr[urlArr.length-1]; //獲取檔名
input type=file在個瀏覽器中樣式各不相同,如下圖所示:
若要統一樣式,可將原有樣式設定屬性 opacity: 0,佈局上用定位position:relative/absolute實現,具體實現程式碼如下:
<!DOCTYPE html> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <script src="./jquery-1.12.0.min.js"></script> <style> .fileIpt { width: 423px; height: 30px; } input { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .label-text[for = "inputDataBackup1"] { color: #0e0e0e; padding: 5px 20px 6px 20px; margin-bottom: 0px; font-weight: 500; background: #2fc8f6; border-radius: 3px 0px 0px 3px; -webkit-border-radius: 3px 0px 0px 3px; -moz-border-radius: 3px 0px 0px 3px; font-size: 14px; vertical-align: middle; text-align: center; } #inputDataBackup1 { width: 268px; height: 30px; background: transparent; position: relative; display: inline-block; margin-left: -6px; padding: 1px 0px 0px 0px; color: #57D1F7; text-align: center; vertical-align: middle; border: 2px solid #2fc8f6; border-radius: 3px; -webkit-border-radius: 3px; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .selectFile { position: absolute; left: 0; top: -1px; z-index: 3; height: 30px; width: 268px; opacity: 0; } .errTip { position: absolute; top: 20px; left: 50%; margin-left: -90px; color: red; font-size: 12px; } .fileName { width: 210px; height: 30px; position: absolute; left: 0; top: -2px; z-index: 1; color: #000; text-align: center; background-color: transparent; border-color: transparent; overflow: hidden; text-overflow: ellipsis; } .path { width: 55px; height: 30px; background-color: #2fc8f6; display: inline-block; position: absolute; top: -2px; right: 0; z-index: -1; text-align: center; vertical-align: middle; border-radius: 0px 3px 3px 0px; -webkit-border-radius: 0px 3px 3px 0px; -moz-border-radius: 0px 3px 3px 0px; } .pathText { display: inline-block; font-size: 30px; line-height: 30px; color: #fff; letter-spacing: 3px; margin-top: -10px; } </style> </head> <body> <div class="fileIpt"> <label class="label-text" for="inputDataBackup1">選擇檔案</label> <div id="inputDataBackup1" class="input-selectStyle"> <input class="selectFile" type="file" title="未選擇任何檔案"> <p class="errTip"></p><input class="fileName" readonly="readonly"> <div class="path"> <span class="pathText">...</span> </div> </div> </div> <script type="text/javascript"> $(".selectFile").on("change",function(){ let filePath = $(this).val(); let urlArr = filePath.split("\\"); let fileName = urlArr[urlArr.length-1]; $(".fileName").val(fileName); $(this).attr("title",fileName); if(fileName == "") { $(".errTip").html("請選擇上傳檔案"); }else{ $(".errTip").html(""); } }) </script> </body> </html>