【问题标题】:css hide "Choose File" button but display file after selectcss隐藏“选择文件”按钮但选择后显示文件
【发布时间】:2016-06-19 13:35:02
【问题描述】:

我想为图片上传制作自定义按钮。我可以通过下面的演示得到这个结果:

https://jsfiddle.net/algometrix/fgrbyo4z/

但是如何显示之后选择的文件名?或者如果可能的话,甚至是图像的缩略图?就像我从弹出的窗口中选择一个文件后,我希望它在我选择它后在页面上显示“文件名”。

Javascript - 如果有人可以在该领域提供帮助,那么 jQuery 完全是一个选择。

HTML

<div>
  <div style="display:block;text-align:center;margin-top:20%;">
    <label for="files"> <span class="btn">Select Image</span></label>
    <input style="visibility: hidden; position: absolute;" id="files" class="form-control" type="file" name="files">

  </div>

</div>

CSS

.btn {
  font-family: Arial;
  color: #ffffff;
  font-size: 20px;
  background: #3f88b8;
  padding: 10px 20px 10px 20px;
  text-decoration: none;
}

.btn:hover {
  background: #3cb0fd;
  background-image: -webkit-linear-gradient(top, #3cb0fd, #3498db);
  background-image: -moz-linear-gradient(top, #3cb0fd, #3498db);
  background-image: -ms-linear-gradient(top, #3cb0fd, #3498db);
  background-image: -o-linear-gradient(top, #3cb0fd, #3498db);
  background-image: linear-gradient(to bottom, #3cb0fd, #3498db);
  text-decoration: none;
}

【问题讨论】:

标签: javascript jquery html css file


【解决方案1】:

通过添加javascript,我们可以只关注输入中的change 事件,并将名称放在页面上。请注意这些微小的 HTML 更改:

<div class="file-upload">
  <label for="upload-1" class="btn">Upload</label>
  <input type="file" id="upload-1">
  <p class="file-name">Please select a file.</p>
</div>

使用这个 jQuery:

jQuery(function($) {
  $('input[type="file"]').change(function() {
    if ($(this).val()) {
         var filename = $(this).val();
         $(this).closest('.file-upload').find('.file-name').html(filename);
    }
  });
});

Working Fiddle

【讨论】:

    【解决方案2】:

    只需点击文件元素的更改事件:

     var file = document.getElementById("files");
     file.addEventListener("change", function(){ alert(this.value); });
    

    显示在这个小提琴中:https://jsfiddle.net/pbg44bqu/12/

    【讨论】:

      【解决方案3】:

      此脚本在上传后立即显示图像:

      function readURL(input) {
      
          if (input.files && input.files[0]) {
              var reader = new FileReader();
      
              reader.onload = function (e) {
                  $('#img').show().attr('src', e.target.result);
              }
      
              reader.readAsDataURL(input.files[0]);
          }
      }
      
      $("#files").change(function(){
          readURL(this);
      });
      

      Source

      Updated Fiddle

      【讨论】:

      • 感谢 WcPc,我有一个简单的问题。如何通过我设置的表格发送此图像?就像我可以让javascript将此文件添加到我的表单数据中,然后当我提交表单时,我可以将此图像作为我当前表单的数据发送吗?
      • 你不需要js,只需在它周围添加表单标签:&lt;form action="my.php" method="post"&gt;,然后在你的PHP中(我假设你使用PHP):var your_file = $_POST['control_name']例如var your_file = $_POST['files']即使您已经显示了图像,它仍然在您的文件上传控件中被选中...
      猜你喜欢
      • 2015-09-20
      • 1970-01-01
      • 1970-01-01
      • 2015-01-09
      • 2014-09-11
      • 2012-12-30
      • 1970-01-01
      • 2021-02-16
      • 1970-01-01
      相关资源
      最近更新 更多