【问题标题】:How to customize <input type="file">?如何自定义 <input type="file">?
【发布时间】:2011-08-14 09:01:02
【问题描述】:

&lt;input type="file"&gt;的外观可以改吗?

【问题讨论】:

  • 文本字段存在的原因是因为它在用户浏览并选择文件后向用户显示文件路径。
  • Oooppss.. 似乎是 Firefox 处理它的方式......
  • 我们很清楚,即使他们浏览了文件,他们仍然必须使用表单提交按钮提交表单。

标签: html css file-upload input


【解决方案1】:

您不能对input[type=file] 控件本身进行太多修改。

由于单击与输入正确配对的label 元素将激活/聚焦它,我们可以使用label 来触发操作系统浏览对话框。

你可以这样做……

label {
   cursor: pointer;
   /* Style as you please, it will become the visible UI component. */
}

#upload-photo {
   opacity: 0;
   position: absolute;
   z-index: -1;
}
<label for="upload-photo">Browse...</label>
<input type="file" name="photo" id="upload-photo" />

表单控件的 CSS 将使它看起来不可见并且不占用文档布局中的空间,但仍将存在,因此可以通过label 激活它。

如果您想在选择后显示用户选择的路径,您可以使用 JavaScript 监听 change 事件,然后读取浏览器为您提供的路径(出于安全原因,它可以撒谎 em> 告诉你确切的路径)。一种让最终用户看起来更漂亮的方法是简单地使用返回的路径的基本名称(这样用户只会看到选择的文件名)。

有一个great guide by Tympanus 用于设置样式。

【讨论】:

  • 我相信,这些是更好的样式,考虑到我们的目标是通过单击容器上的任意位置来打开选择文件对话框:#container { position: relative; width: ...px; height: ...px; overflow: hidden; } #input { position: absolute; right: 0; font-size: &lt;many a&gt;px; opacity: 0; margin: 0; padding: 0; border: none; }
  • Using &lt;label&gt; (as shown by Tympanus) 更加语义化,不那么骇人听闻。此外,几年后再次提出了这个问题,并且在那里有更好的答案:cross-browser custom styling for file upload button
  • @DanDascalescu 我同意,如果我没记错的话(早在 2011 年),它在 IE 上存在问题,可能是 6 或 7 个。我现在将编辑这个答案以将其引入未来。
  • 为什么使用标签更好?您不能使用标签标签,此外,按钮对我来说比激活对话框的标签更有意义。
  • @alex,它没有显示文件名。
【解决方案2】:

可能是这样的吗?

<form>
  <input id="fileinput" type="file" style="display:none;"/>
</form>
<button id="falseinput">El Cucaratcha, for example</button>
<span id="selected_filename">No file selected</span>

<script>
$(document).ready( function() {
  $('#falseinput').click(function(){
    $("#fileinput").click();
  });
});
$('#fileinput').change(function() {
  $('#selected_filename').text($('#fileinput')[0].files[0].name);
});

</script>

【讨论】:

  • 在这种情况下 ie 9 将不允许将表单发送到 iframe。
  • @x-yuri 你是什么意思?
  • 据我记得,ie 9(可能还有其他)不允许将表单发送到 iframe,因为用户没有点击输入文件。
  • display: none 将从标签顺序中删除输入,使页面更难访问。 Using &lt;label&gt; (as shown by Tympanus) 更加语义化且不那么骇人听闻。此外,这个问题在几年后再次被问到并且有更好的答案:cross-browser custom styling for file upload button
  • 修复了选择器中的右方括号拼写错误,以使代码实际工作
【解决方案3】:
  <label for="fusk">dsfdsfsd</label>
  <input id="fusk" type="file" name="photo" style="display: none;">

为什么不呢? ^_^

查看示例here

【讨论】:

【解决方案4】:

如果您使用 Bootstrap,这里有一个更好的解决方案:

<label class="btn btn-default btn-file">
    Browse <input type="file" style="display: none;" required>
</label>

IE8及以下:https://www.abeautifulsite.net/posts/whipping-file-inputs-into-shape-with-bootstrap-3/#legacy-approach-(ie8-and-below)

来源:https://stackoverflow.com/a/18164555/625952

【讨论】:

  • 我在使用引导程序时遇到了很多麻烦。在手机上,每当我点击完成照片的勾号时,表单就会提交,没有照片,而不是等待提交按钮。目前我有:&lt;label class="btn btn-default btn-file"&gt; &lt;input onchange="alert('Please check picture is OK')"; type="file" required&gt; &lt;/label&gt;和一些 javascript 来检查必填字段,作为引导示例。
【解决方案5】:

最简单的方法..

<label>
     Upload
    <input type="file" style="visibility: hidden;"/>
</label>

【讨论】:

  • style="display:none;" 的可见性要好得多:隐藏
【解决方案6】:

诀窍是隐藏输入并自定义标签。

HTML:

<div class="inputfile-box">
  <input type="file" id="file" class="inputfile" onchange='uploadFile(this)'>
  <label for="file">
    <span id="file-name" class="file-box"></span>
    <span class="file-button">
      <i class="fa fa-upload" aria-hidden="true"></i>
      Select File
    </span>
  </label>
</div>

CSS:

.inputfile-box {
  position: relative;
}

.inputfile {
  display: none;
}

.container {
  display: inline-block;
  width: 100%;
}

.file-box {
  display: inline-block;
  width: 100%;
  border: 1px solid;
  padding: 5px 0px 5px 5px;
  box-sizing: border-box;
  height: calc(2rem - 2px);
}

.file-button {
  background: red;
  padding: 5px;
  position: absolute;
  border: 1px solid;
  top: 0px;
  right: 0px;
}

JS:

function uploadFile(target) {
    document.getElementById("file-name").innerHTML = target.files[0].name;
}

你可以查看这个例子:https://jsfiddle.net/rjurado/hnf0zhy1/4/

【讨论】:

    【解决方案7】:

    在 webkit 中你可以试试这个...

    input[type="file"]::-webkit-file-upload-button{
       /* style goes here */
    }
    

    【讨论】:

    • 你知道火狐有什么类似的解决方案吗?它存在吗? )
    【解决方案8】:

    首先它是一个容器:

    <div class="upload_file_container">
        Select file!
        <input type="file" name="photo" />
    </div>
    

    第二个,它是CSS样式,如果你想真正更多的定制,睁大眼睛就好了:)

    .upload_file_container{
       width:100px;
       height:40px;
       position:relative;
       background(your img);
    }
    
    .upload_file_container input{
       width:100px;
       height:40px;
       position:absolute;
       left:0;
       top:0;
       cursor:pointer;
    }
    

    这个例子没有按钮内文本的样式,它取决于字体大小,只需更正容器的高度和填充顶部值

    【讨论】:

    • 我想知道你为什么不做right: 0,而不是left: 0?这样,您就可以将 ie 的文本框从容器中取出。单击文本框不会打开选择文件对话框。另外,我相信使用font-size 使输入文件变大是更好的主意,然后使用widthheight
    【解决方案9】:

    如果你只使用&lt;label&gt;,隐藏&lt;input&gt;,并自定义标签会更好。

    HTML:

    <input type="file" id="input">
    <label for="input" id="label">Choose File</label>
    

    CSS:

    input#input{
        display: none;
    }
    label#label{
        /* Customize your label here */
    }
    

    【讨论】:

    【解决方案10】:

    引导示例

    <label className="btn btn-info btn-lg">
      Upload
      <input type="file" style="display: none" />
    </label>
    

    【讨论】:

      【解决方案11】:

      要显示所选文件的路径,你可以试试这个 在 html 上:

      <div class="fileinputs">
          <input type="file" class="file">
      </div>
      

      在 javascript 中:

              var fakeFileUpload = document.createElement('div');
              fakeFileUpload.className = 'fakefile';
              var image = document.createElement('div');
              image.className='fakebtn';
              image.innerHTML = 'browse';
              fakeFileUpload.appendChild(image);
              fakeFileUpload.appendChild(document.createElement('input'));
              var x = document.getElementsByTagName('input');
              for (var i=0;i<x.length;i++) {
                  if (x[i].type != 'file') continue;
                  if (x[i].parentNode.className != 'fileinputs') continue;
                  x[i].className = 'file hidden';
                  var clone = fakeFileUpload.cloneNode(true);
                  x[i].parentNode.appendChild(clone);
                  x[i].relatedElement = clone.getElementsByTagName('input')[0];
                  x[i].onchange = x[i].onmouseout = function () {
                      this.relatedElement.value = this.value;
                  }
              }
      

      和风格:

      div.fileinputs {
          position: relative;
          height: 30px;
          width: 370px;
      }
      input.file.hidden {
          position: relative;
          text-align: right;
          -moz-opacity: 0;
          filter: alpha(opacity: 0);
          opacity: 0;
          z-index: 2;
      }
      div.fakefile {
          position: absolute;
          top: 0px;
          left: 0px;
          right: 0;
          width: 370px;
          padding: 0;
          margin: 0;
          z-index: 1;
          line-height: 90%;
      }
      div.fakefile input {
          margin-bottom: 5px;
          margin-left: 0;
          border: none;
          box-shadow: 0px 0px 2px 1px #ccc;
          padding: 4px;
          width: 241px;
          height: 20px;
      }
      div.fakefile .fakebtn{
          width: 150px;
          background: #eb5a41;
          z-index: 10;
          font-family: roya-bold;
          border: none;
          padding: 5px 15px;
          font-size: 18px;
          text-align: center;
          cursor: pointer;
          -webkit-transition: all 0.4s ease;
          -moz-transition: all 0.4s ease;
          -o-transition: all 0.4s ease;
          -ms-transition: all 0.4s ease;
          transition: all 0.4s ease;
          display: inline;
          margin-left: 3px;
      }
      div.fileinputs input[type="file"]:hover + div .fakebtn{
          background: #DA472E;
      }
      
      div.fileinputs input[type="file"] {
          opacity: 0;
          position: absolute;
          top: -6px;
          right: 0px;
          z-index: 20;
          width: 102px;
          height: 40px;
          cursor: pointer;
      }
      

      【讨论】:

        【解决方案12】:

        这是一个快速的纯 CSS 解决方法(适用于 chrome 并包含 FireFox 后备),包括文件名、标签和自定义上传按钮,可以做它应该做的 - 根本不需要 JavaScript! ?

        注意:☝ 这适用于 Chrome 并且有 FireFox 后备 - 无论如何,我不会在真实世界的网站上使用它 - 如果浏览器兼容性对你来说是一件事情(它应该是什么)。所以它更像是一种实验性的。

        .fileUploadInput {
          display: grid;
          grid-gap: 10px;
          position: relative;
          z-index: 1; }
          
          .fileUploadInput label {
            display: flex;
            align-items: center;
            color: setColor(primary, 0.5);
            background: setColor(white);
            transition: .4s ease;
            font-family: arial, sans-serif;
            font-size: .75em;
            font-weight: regular; }
            
          .fileUploadInput input {
            position: relative;
            z-index: 1;
            padding: 0 gap(m);
            width: 100%;
            height: 50px;
            border: 1px solid #323262;
            border-radius: 3px;
            font-family: arial, sans-serif;
            font-size: 1rem;
            user-select: none;
            cursor: pointer;
            font-weight: regular; }
            .fileUploadInput input[type="file"] {
              padding: 0 gap(m); }
              .fileUploadInput input[type="file"]::-webkit-file-upload-button {
                visibility: hidden;
                margin-left: 10px;
                padding: 0;
                height: 50px;
                width: 0; }
                
          .fileUploadInput button {
            position: absolute;
            right: 0;
            bottom: 0;
            width: 50px;
            height: 50px;
            line-height: 0;
            user-select: none;
            color: white;
            background-color: #323262;
            border-radius: 0 3px 3px 0;
            font-family: arial, sans-serif;
            font-size: 1rem;
            font-weight: 800; }
            .fileUploadInput button svg {
              width: auto;
              height: 50%; }
        
        * {
          margin: 0px;
          padding: 0px;
          box-sizing: border-box;
          border: 0px;
          outline: 0;
          background-repeat: no-repeat;
          appearance: none;
          border-radius: 0;
          vertical-align: middle;
          font-weight: inherit;
          font-style: inherit;
          font-family: inherit;
          text-decoration: none;
          list-style: none;
          user-select: text;
          line-height: 1.333em; }
        
        body {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 100%;
          height: 100vh;
          background: rgba(66, 50, 98, 0.05); }
        
        .container {
          padding: 25px;
          box-shadow: 0 0 20px rgba(66, 50, 98, 0.35);
          border: 1px solid #eaeaea;
          border-radius: 3px;
          background: white; }
        
        @-moz-document url-prefix() {
        .fileUploadInput button{
            display: none
        }
        }
        <!-- Author: Ali Soueidan-->
        <!-- Author URI: https//: www.alisoueidan.com-->
        
        <div class="container">
            <div class="fileUploadInput">
            <label>✨ Upload File</label>
            <input type="file" />
            <button>+</button></div>
        </div>

        【讨论】:

        • 这是完美的,也是迄今为止我见过的最好的。快速提问,有没有办法不显示整个文件名,例如,如果文件名太长,它会超过“+”
        • @ReneChan 您可以使用 CSS 将文件名上的“溢出”设置为“省略号”或“隐藏”。
        【解决方案13】:

        这是我喜欢的一种方式,因为它使输入填满整个容器。诀窍是“font-size: 100px”,它需要配合“overflow: hidden”和相对位置。

        <div id="upload-file-container" >
           <input type="file" />
        </div>
        
        #upload-file-container {
           width: 200px;
           height: 50px;
           position: relative;
           border: dashed 1px black;
           overflow: hidden;
        }
        
        #upload-file-container input[type="file"]
        {
           margin: 0;
           opacity: 0;   
           font-size: 100px;
        }
        

        【讨论】:

        • 搞定position: absolute; right: 0; font-size: &lt;many&gt;px;是有意义的
        【解决方案14】:

        我选择了这个选项,它阐明了如何通过包含上传文件名的处理程序来完全自定义浏览按钮,也是自定义的。 它在它们上添加了额外的字段和客户端控件,只是为了展示如何以“真实”形式包含浏览,而不仅仅是独立的。

        这是代码笔:http://codepen.io/emiemi/pen/zxNXWR

        JS:

        //click on our custom btn triggers a click on the hidden actual file input 
        $("#btnup").click(function(){
           $("#fileup").click();    
        });
        
        
        //changes on the three fields (input, tit,and name) trigger a control which checks if the 3 fields are all filled and if file field is valid (an image is uploaded)
        $('#fileup').change(function(){
            var formDOMObj = document.upload;
        //here we assign tu our text field #fileup the name of the selected file  
            var res=$('#fileup').val();
            var arr = res.split("\\");
        //if file is not valid we show the error icon and the red alert
            if (formDOMObj.fileup.value.indexOf(".jpg") == -1 && formDOMObj.fileup.value.indexOf(".png") == -1 &&  formDOMObj.fileup.value.indexOf(".jpeg") == -1 && formDOMObj.fileup.value.indexOf(".bmp") == -1 && formDOMObj.fileup.value.indexOf(".JPG") == -1 && formDOMObj.fileup.value.indexOf(".PNG") == -1 &&  formDOMObj.fileup.value.indexOf(".JPEG") == -1 && formDOMObj.fileup.value.indexOf(".BMP") == -1){
                $( ".imgupload" ).hide("slow"); 
                $( ".imguploadok" ).hide("slow");   
                $( ".imguploadstop" ).show("slow");
                $('#nomefile').css({"color":"red","font-weight":700});
                $('#nomefile').html("The file "+arr.slice(-1)[0]+" is not an image!");
                $( "#bottone" ).hide();
                $( "#fakebtn" ).show();
            }else{
         //if file is valid we show the green alert
            $( ".imgupload" ).hide("slow");
            $( ".imguploadstop" ).hide("slow");
            $( ".imguploadok" ).show("slow");
            $('#nomefile').html(arr.slice(-1)[0]);
            $('#nomefile').css({"color":"green","font-weight":700});
            if (formDOMObj.nome.value!=""&&formDOMObj.tit.value!=""&&formDOMObj.fileup.value!=""){
          //if all three fields are valid the fake input btn is hidden and the actual one i s finally hown
                $( "#fakebtn" ).hide();
                $( "#bottone" ).show();
            }
            }
        });
        
        
        $('#nome').change(function(){
        //same as file change but on name field
            var formDOMObj = document.upload;
            if (formDOMObj.nome.value!=""&&formDOMObj.tit.value!=""&&formDOMObj.fileup.value!=""){
                $( "#fakebtn" ).hide();
                $( "#bottone" ).show();
            }else{
                $( "#bottone" ).hide();
                $( "#fakebtn" ).show();
            }
        });
        $('#tit').change(function(){
         //same as file change but on tit field
            var formDOMObj = document.upload;
            if (formDOMObj.nome.value!=""&&formDOMObj.tit.value!=""&&formDOMObj.fileup.value!=""){
                $( "#fakebtn" ).hide();
                $( "#bottone" ).show();
            }else{
                $( "#bottone" ).hide();
                $( "#fakebtn" ).show();
            }
        });
        

        HTML:

        <form name="upload" method="post" action="/" enctype="multipart/form-data" accept-charset="utf-8">
        <div class="row">
          <div class="col-md-6 center">
        <!--this is the actual file input, s hidden beacause we wanna use our custom one-->
            <input type="file" value="" class="hidden" name="fileup" id="fileup">
            <div class="btn-container">
        <!--the three icons: default, ok file (img), error file (not an img)-->
              <h1 class="imgupload"><i class="fa fa-file-image-o"></i></h1>
              <h1 class="imguploadok"><i class="fa fa-check"></i></h1>
              <h1 class="imguploadstop"><i class="fa fa-times"></i></h1>
        <!--this field changes dinamically displaying the filename we are trying to upload-->
              <p id="nomefile">Only pics allowed! (jpg,jpeg,bmp,png)</p>
        <!--our custom btn which triggers the actual hidden one-->
              <button type="button" id="btnup" class="btn btn-primary btn-lg">Browse for your pic!</button>
            </div>
          </div>
        <!--additional fields-->
          <div class="col-md-6">
            <div class="row">
              <div class="form-group" id="top">
                <div class="col-md-12">
                  <input type="text" maxlength="100" class="form-control" name="nome" id="nome" placeholder="Your Name">
                </div>
              </div>
            </div>
            <div class="row">
              <div class="form-group">
                <div class="col-md-12">
                  <input type="text" maxlength="50" class="form-control" name="tit" id="tit" placeholder="I am rubber, you are glue">
                </div>
              </div>
            </div>
        
            <div class="row">
              <div class="col-md-8">
                <p class="white">All fields are mandatory</p>
              </div>
              <div class="col-md-4">
        <!--the defauld disabled btn and the actual one shown only if the three fields are valid-->
                <input type="submit" value="Submit!" class="btn btn-primary" id="bottone" style="padding-left:50px; padding-right:50px; display:none;">
                <button type="button" class="btn btn-default" disabled="disabled" id="fakebtn"  style="padding-left:40px; padding-right:40px;">Submit! <i class="fa fa-minus-circle"></i></button>
              </div>
            </div>
          </div>
        </div>
        

        【讨论】:

          【解决方案15】:

          您可以设置它们的样式,但不能删除已经存在的元素。如果您有创意,您可以使用它并执行以下操作:

          input[type=file] {
              -webkit-appearance: none;
              -moz-appearance: none;
              appearance: none;
              background: #EEE;
              background: linear-gradient(to top, #FFF, #DDD);
              border: thin solid rgba(0,0,0, .5);
              border-radius: .25em;
              box-shadow: inset .25em .25em .25em rgba(255,255,255, .5), inset -.1em -.1em .1em rgba(0,0,0, 0.1);
              cursor: text;
              padding: .25em;
          }
          

          http://jsfiddle.net/zr1x1m2b/1/

          我建议你使用这段代码,删除行,添加你自己的,做任何事情,直到你得到你喜欢的东西!

          【讨论】:

          【解决方案16】:

          使用您最喜欢的 CSS 为普通按钮设置任何您想要的样式。

          然后调用一个简单的 JS 函数来创建一个隐藏的输入元素并将其链接到您的样式按钮。不要添加特定于浏览器的 CSS 来做隐藏部分。

          <!DOCTYPE html>
          <meta charset="utf-8">
          
          <style>
              button {
                  width            : 160px;
                  height           : 30px;
                  font-size        : 13px;
                  border           : none;
                  text-align       : center;
                  background-color : #444;
                  color            : #6f0;
              }
              button:active {
                  background-color : #779;
              }
          </style>
          
          <button id="upload">Styled upload button!</button>
          
          <script>
          
          function Upload_On_Click(id, handler) {
              var hidden_input = null;
              document.getElementById(id).onclick = function() {hidden_input.click();}
              function setup_hidden_input() {
                  hidden_input && hidden_input.parentNode.removeChild(hidden_input);
                  hidden_input = document.createElement("input");
                  hidden_input.setAttribute("type", "file");
                  hidden_input.style.visibility = "hidden";
                  document.querySelector("body").appendChild(hidden_input);
                  hidden_input.onchange = function() {
                      handler(hidden_input.files[0]);
                      setup_hidden_input();
                  };
              }
              setup_hidden_input();
          }
          
          Upload_On_Click("upload", function(file) {
              console.log("GOT FILE: " + file.name);
          });
          
          </script>
          

          请注意,每次用户选择文件后,上述代码如何重新链接它。这很重要,因为只有在用户更改文件名时才会调用“onchange”。但您可能希望每次用户提供文件时都获取该文件。

          有关更多详细信息,请研究 DropZone 和 gmail 上传。

          【讨论】:

            【解决方案17】:

             $(document).ready(function () {
                    $(document).mousemove(function () {
                    $('#myList').css('display', 'block');
                    $("#seebtn").css('display', 'none');
                    $("#hidebtn").css('display', 'none');
                    $('#displayFileNames').html('');
                    $("#myList").html('');
                    var fileArray1 = document.getElementsByClassName('file-input');
                    for (var i = 0; i < fileArray1.length; i++) {
                        var files = fileArray1[i].files;
                        for (var j = 0; j < files.length; j++) {
                            $("#myList").append("<li style='color:black'>" + files[j].name + "</li>");
                        }
                    };
            
                    if (($("#myList").html()) != '') {
                        $('#unselect').css('display', 'block');
                        $('#divforfile').css('color', 'green');
                        $('#attach').css('color', 'green');
                        $('#displayFileNames').html($("#myList").children().length + ' ' + 'files selezionato');
            
                    };
            
                    if (($("#myList").html()) == '') {
                        $('#divforfile').css('color', 'black');
                        $('#attach').css('color', 'black');
                        $('#displayFileNames').append('Nessun File Selezionato');
                    };
                });
            
              });
            
              function choosefiles(obj) {
                    $(obj).hide();
                    $('#myList').css('display', 'none');
                    $('#hidebtn').css('display', 'none');
                    $("#seebtn").css('display', 'none');
                    $('#unselect').css('display', 'none');
                    $("#upload-form").append("<input class='file-input inputs' type='file' onclick='choosefiles(this)' name='file[]' multiple='multiple' />");
                    $('#displayFileNames').html('');
                }
            
              $(document).ready(function () {
                    $('#unselect').click(function () {
                        $('#hidebtn').css('display', 'none');
                        $("#seebtn").css('display', 'none');
                        $('#displayFileNames').html('');
                        $("#myList").html('');
                        $('#myFileInput').val('');
                        document.getElementById('upload-form').reset();         
                        $('#unselect').css('display', 'none');
                        $('#divforfile').css('color', 'black');
                        $('#attach').css('color', 'black');
            
                    });
                });
            <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
            
            <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
            <style>
              .divs {
                    position: absolute;
                    display: inline-block;
                    background-color: #fff;
                }
            
                .inputs {
                    position: absolute;
                    left: 0px;
                    height: 2%;
                    width: 15%;
                    opacity: 0;
                    background: #00f;
                    z-index: 100;
                }
            
                .icons {
                    position: absolute;
                }
            
             </style>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
                        <div>
                            <form id='upload-form' action='' method='post' enctype='multipart/form-data'>
                               
                                <div class="divs" id="divforfile" style="color:black">
                                    <input id='myFileInput' class='file-input inputs' type='file' name='file[]' onclick="choosefiles(this)" multiple='multiple' />
                                    <i class="material-icons" id="attach" style="font-size:21px;color:black">attach_file</i><label>Allegati</label>
                                </div>
                            </form>
                            <br />
                        </div>
                        <br />  
                        <div>
                            <button style="border:none; background-color:white; color:black; display:none" id="seebtn"><p>Files &#9660;</p></button>
                            <button style="border:none; background-color:white; color:black; display:none" id="hidebtn"><p>Files &#9650;</p></button>
                            <button type="button" class="close" aria-label="Close" id="unselect" style="display:none;float:left">
                                <span style="color:red">&times;</span>
                            </button>
                            <div id="displayFileNames">
                            </div>
                            <ul id="myList"></ul>
                        </div>

            这是我使用 jquery 和 javascript (Visual Studio) 的全功能定制文件上传/附件。这会很有用!

            代码将在评论部分提供!

            链接:https://youtu.be/It38OzMAeig

            享受:)

             $(document).ready(function () {
                    $(document).mousemove(function () {
                    $('#myList').css('display', 'block');
                    $("#seebtn").css('display', 'none');
                    $("#hidebtn").css('display', 'none');
                    $('#displayFileNames').html('');
                    $("#myList").html('');
                    var fileArray1 = document.getElementsByClassName('file-input');
                    for (var i = 0; i < fileArray1.length; i++) {
                        var files = fileArray1[i].files;
                        for (var j = 0; j < files.length; j++) {
                            $("#myList").append("<li style='color:black'>" + files[j].name + "</li>");
                        }
                    };
            
                    if (($("#myList").html()) != '') {
                        $('#unselect').css('display', 'block');
                        $('#divforfile').css('color', 'green');
                        $('#attach').css('color', 'green');
                        $('#displayFileNames').html($("#myList").children().length + ' ' + 'files selezionato');
            
                    };
            
                    if (($("#myList").html()) == '') {
                        $('#divforfile').css('color', 'black');
                        $('#attach').css('color', 'black');
                        $('#displayFileNames').append('Nessun File Selezionato');
                    };
                });
            
              });
            
              function choosefiles(obj) {
                    $(obj).hide();
                    $('#myList').css('display', 'none');
                    $('#hidebtn').css('display', 'none');
                    $("#seebtn").css('display', 'none');
                    $('#unselect').css('display', 'none');
                    $("#upload-form").append("<input class='file-input inputs' type='file' onclick='choosefiles(this)' name='file[]' multiple='multiple' />");
                    $('#displayFileNames').html('');
                }
            
              $(document).ready(function () {
                    $('#unselect').click(function () {
                        $('#hidebtn').css('display', 'none');
                        $("#seebtn").css('display', 'none');
                        $('#displayFileNames').html('');
                        $("#myList").html('');
                        $('#myFileInput').val('');
                        document.getElementById('upload-form').reset();         
                        $('#unselect').css('display', 'none');
                        $('#divforfile').css('color', 'black');
                        $('#attach').css('color', 'black');
            
                    });
                });
            <style>
              .divs {
                    position: absolute;
                    display: inline-block;
                    background-color: #fff;
                }
            
                .inputs {
                    position: absolute;
                    left: 0px;
                    height: 2%;
                    width: 15%;
                    opacity: 0;
                    background: #00f;
                    z-index: 100;
                }
            
                .icons {
                    position: absolute;
                }
            
             </style>
            <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
               <div>
                            <form id='upload-form' action='' method='post' enctype='multipart/form-data'>
                               
                                <div class="divs" id="divforfile" style="color:black">
                                    <input id='myFileInput' class='file-input inputs' type='file' name='file[]' onclick="choosefiles(this)" multiple='multiple' />
                                    <i class="material-icons" id="attach" style="font-size:21px;color:black">attach_file</i><label>Allegati</label>
                                </div>
                            </form>
                            <br />
                        </div>
                        <br />  
                        <div>
                            <button style="border:none; background-color:white; color:black; display:none" id="seebtn"><p>Files &#9660;</p></button>
                            <button style="border:none; background-color:white; color:black; display:none" id="hidebtn"><p>Files &#9650;</p></button>
                            <button type="button" class="close" aria-label="Close" id="unselect" style="display:none;float:left">
                                <span style="color:red">&times;</span>
                            </button>
                            <div id="displayFileNames">
                            </div>
                            <ul id="myList"></ul>
                        </div>

            <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
             $(document).ready(function () {
                    $(document).mousemove(function () {
                    $('#myList').css('display', 'block');
                    $("#seebtn").css('display', 'none');
                    $("#hidebtn").css('display', 'none');
                    $('#displayFileNames').html('');
                    $("#myList").html('');
                    var fileArray1 = document.getElementsByClassName('file-input');
                    for (var i = 0; i < fileArray1.length; i++) {
                        var files = fileArray1[i].files;
                        for (var j = 0; j < files.length; j++) {
                            $("#myList").append("<li style='color:black'>" + files[j].name + "</li>");
                        }
                    };
            
                    if (($("#myList").html()) != '') {
                        $('#unselect').css('display', 'block');
                        $('#divforfile').css('color', 'green');
                        $('#attach').css('color', 'green');
                        $('#displayFileNames').html($("#myList").children().length + ' ' + 'files selezionato');
            
                    };
            
                    if (($("#myList").html()) == '') {
                        $('#divforfile').css('color', 'black');
                        $('#attach').css('color', 'black');
                        $('#displayFileNames').append('Nessun File Selezionato');
                    };
                });
            
              });
            
              function choosefiles(obj) {
                    $(obj).hide();
                    $('#myList').css('display', 'none');
                    $('#hidebtn').css('display', 'none');
                    $("#seebtn").css('display', 'none');
                    $('#unselect').css('display', 'none');
                    $("#upload-form").append("<input class='file-input inputs' type='file' onclick='choosefiles(this)' name='file[]' multiple='multiple' />");
                    $('#displayFileNames').html('');
                }
            
              $(document).ready(function () {
                    $('#unselect').click(function () {
                        $('#hidebtn').css('display', 'none');
                        $("#seebtn").css('display', 'none');
                        $('#displayFileNames').html('');
                        $("#myList").html('');
                        $('#myFileInput').val('');
                        document.getElementById('upload-form').reset();         
                        $('#unselect').css('display', 'none');
                        $('#divforfile').css('color', 'black');
                        $('#attach').css('color', 'black');
            
                    });
                });
            <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
            <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
            <style>
              .divs {
                    position: absolute;
                    display: inline-block;
                    background-color: #fff;
                }
            
                .inputs {
                    position: absolute;
                    left: 0px;
                    height: 2%;
                    width: 15%;
                    opacity: 0;
                    background: #00f;
                    z-index: 100;
                }
            
                .icons {
                    position: absolute;
                }
            
             </style>
             <div>
                            <form id='upload-form' action='' method='post' enctype='multipart/form-data'>
                               
                                <div class="divs" id="divforfile" style="color:black">
                                    <input id='myFileInput' class='file-input inputs' type='file' name='file[]' onclick="choosefiles(this)" multiple='multiple' />
                                    <i class="material-icons" id="attach" style="font-size:21px;color:black">attach_file</i><label>Allegati</label>
                                </div>
                            </form>
                            <br />
                        </div>
                        <br />  
                        <div>
                            <button style="border:none; background-color:white; color:black; display:none" id="seebtn"><p>Files &#9660;</p></button>
                            <button style="border:none; background-color:white; color:black; display:none" id="hidebtn"><p>Files &#9650;</p></button>
                            <button type="button" class="close" aria-label="Close" id="unselect" style="display:none;float:left">
                                <span style="color:red">&times;</span>
                            </button>
                            <div id="displayFileNames">
                            </div>
                            <ul id="myList"></ul>
                        </div>

            【讨论】:

              【解决方案18】:

              这是我最近发现的一种方法,带有一点 jQuery

              HTML 代码:

              <form action="">
                  <input type="file" name="file_upload" style="display:none" id="myFile">
              
                  <a onclick="fileUpload()"> Upload a file </a>
              </form>
              

              对于 javascript/jQuery 部分:

              <script>
              function fileUpload() {
                  $("#myFile").click();
              }
              </script>
              

              在这个例子中,我放置了一个“锚”标签来触发文件上传。您可以替换为任何您想要的,只要记住将“onclick”属性与适当的功能一起使用。

              希望这会有所帮助!

              附: : 不要忘记包含来自 CDN 或任何其他来源的 jQuery

              【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2011-04-06
              • 1970-01-01
              • 2013-12-31
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多