【问题标题】:customizing file upload to look same in all browsers [duplicate]自定义文件上传以在所有浏览器中看起来都一样[重复]
【发布时间】:2013-05-04 00:56:02
【问题描述】:

如何自定义文件上传,

<input type="file" />

在所有浏览器中看起来都一样? 我想在单击我的自定义样式按钮时调用文件浏览器。

【问题讨论】:

标签: javascript jquery html file-upload


【解决方案1】:

对于这样的事情,最好的选择是使用像 Uploadify 这样的插件,不仅可以统一设置上传按钮的样式,还可以添加进度条和多个文件上传。

不幸的是,没有可靠的方法(据我所知)在所有浏览器中一致地设置文件上传样式。这是前端开发人员不喜欢谈论的控件之一。

【讨论】:

  • 有一个可靠的方法来做这个跨浏览器。许多文件上传库已经通过一些 CSS 和 javascript 实现了这一点。
【解决方案2】:

您可以自己重载上传按钮上的样式,方法是将文件上传的不透明度设置为 0,并在顶部放置您想要的样式的 div。例如

    <input style="opacity:0; position: fixed;" onchange="openfile(event)" type="file">
    <div class="icon">Open</div>

【讨论】:

    【解决方案3】:

    一种选择是隐藏真实输入并用按钮替换它。

    $('input[type=file]').each(function(index,input){
    
         var button = $("<button class='file_btn'>Upload File</button>");
         $(input).before(button);
         $(input).css({position:'absolute',top:'-1000px'});
    
         button.click(function(){
             $(input).trigger('click');
         });
    
    });
    

    一个工作小提琴:http://jsfiddle.net/KQhGR/1/

    【讨论】:

      【解决方案4】:

      自己思考了半个小时后找到了一个解决方案,正好解决了这个问题。(是的,我发布这个问题时就知道答案,但想看看其他人如何解决这个问题,当然我想分享我的解决方案其余的)

      工作jsfiddle 示例。

      <input style="float:left; width:270px; height:25px;" id="path" name="path" disabled /> <!--disabled it, to avoid user from editing the file path-->
      <input style="display:none;" type="file" id="photo-path" name="file" placeholder="" /> <!-- hide the default input type='file' coz its ugly :) -->
      
      <button type="submit" onclick="document.getElementById('photo-path').click(); return false;">Browse</button>  <!-- but call hidden input type='file' when user clicks on your custom browse button,  -->
      

      这是 JQuery 代码:(将文件路径复制到您的自定义字段)

      <script type='text/javascript'>
          $('input[name="file"]').change(function(){
              var fileName = $(this).val();
              $('input[name="path"]').val(fileName);
          });
      </script>
      

      【讨论】:

        猜你喜欢
        • 2015-09-27
        • 2017-05-24
        • 2011-06-08
        • 2011-12-02
        • 1970-01-01
        • 1970-01-01
        • 2017-09-28
        • 2021-12-04
        • 2011-05-19
        相关资源
        最近更新 更多