上傳文件按鈕美化,上傳文件前后狀態控制


我們在做input文本上傳的時候,html自帶的上傳按鈕比較丑,如何對其進行美化呢?同理:input checkbox美化,input radio美化是一個道理的.

input file上傳按鈕的美化思路是,先把之前的按鈕透明度opacity設置為0,然后,外層用div包裹,就實現了美化功能。

注:input 的 type 為 file 時,它的 name 必須有值,因為這個 name 會做為上傳文件信息的數組名稱。

<a href="javascript:;" class="a-upload mr10"><input type="file" name="myFiles" id="">點擊這里上傳文件</a>
.a-upload{
                padding: 4px 10px;
                /*height: 34px;*/
                line-height: 28px;
                position: relative;
                cursor: pointer;
                color: #fff;
                background-color: #286090;
                border-color: #204d74;
                border-radius: 4px;
                overflow: hidden;
                display: inline-block;
                *display: inline;
                *zoom: 1;
            }
            .a-upload input{
                position: absolute;
                font-size: 100px;
                right: 0;
                top: 0;
                opacity: 0;
                filter: alpha(opacity=0);
                cursor: pointer
            }
            .a-upload:hover{
                color: #FFFFFF;
                background: #337ab7;
                border-color: #204d74;
                text-decoration: none;
            }

上面美化,把默認選擇文件后,顯示的文件名也給隱藏掉了,那么如何顯示已經選擇的文件名稱呢?沒關系,我們可以用jquery來獲取文件的文件名。

我們可以寫個change事件.

<a href="javascript:;" id="upload" class="a-upload mr10"><input type="file" name="" id="">點擊這里上傳文件</a>
//添加一個顯示文件名稱的div
<div class="showFileName"></div>
//上傳按鈕
<button id="uploadBtn" type="button" class="btn btn-primary">上傳</button>
$(function() {

  //顯示隱藏的文件名並上傳狀態切換
  $('.showFileName').hide();
  $('#uploadBtn').hide();
  $("#upload").on("change", "input[type='file']", function() {
  var filePath = $(this).val();
  //如果僅上傳圖片 if(filePath.indexOf("jpg") != -1 || filePath.indexOf("png") != -1) {
  if(filePath) {
    $(".fileerrorTip").html("").hide();
    var arr = filePath.split('\\');
    var fileName = arr[arr.length - 1];
    $('.showFileName').show();
    $('#uploadBtn').show();
    $(".showFileName").html("已選擇文件名:" + fileName);
    $('#upload').hide();
  } else {
    $(".showFileName").html("");
    $(".fileerrorTip").html("您未上傳文件,或者您上傳文件類型有誤!").show();
    return false
  }
});


});

未選擇文件時

選擇文件后

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM