【问题标题】:How to style "input file" with CSS3 / Javascript? [duplicate]如何使用 CSS3 / Javascript 设置“输入文件”的样式? [复制]
【发布时间】:2011-03-14 15:51:00
【问题描述】:

我想使用 CSS3 设置 <input type="file" /> 的样式。

或者,我希望用户按下div(我将设置样式),这将打开浏览窗口。

是否可以仅使用 HTML、CSS3 和 Javascript / jQuery 来做到这一点?

【问题讨论】:

  • 是的,当然,但我没有找到足够好的解决方案。
  • 看看这个绝招:stackoverflow.com/q/6638434/809356
  • 只需使用this method。它确实是最简单的一种,在所有浏览器中都能完美运行,根本不需要任何 JavaScript。
  • 如果您不想直接处理此处描述的与样式相关的技巧,可以使用 Polymer/Web 组件,并且不需要支持 IE9 或更早版本,请查看我创建的自定义元素:<file-input> github.com/garstasio/file-input。它还为文件输入提供了许多其他功能。

标签: javascript jquery html css file-io


【解决方案1】:

我有一个粗略的例子,你可能想了解一下......

html​

<div id="file">Chose file</div>
<input type="file" name="file" />​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

CSS

#file {
    display:none;
}​

jQuery

var wrapper = $('<div/>').css({height:0,width:0,'overflow':'hidden'});
var fileInput = $(':file').wrap(wrapper);

fileInput.change(function(){
    $this = $(this);
    $('#file').text($this.val());
})

$('#file').click(function(){
    fileInput.click();
}).show();

demo

​​​​​​​​​​​​​​​

【讨论】:

  • 这可能是一个很好的解决方案,但它在 Firefox 中不起作用! fileInput.click(); 不打开对话框。
  • 在 IE 中,当您单击提交时,这将清空所选文件并取消提交(安全功能?),因为用户实际上并没有点击文件输入,任何绕过的方法这? FF4 工作正常。
  • 对于多个文件,同样的想法。仅在 ff 上测试。 jsfiddle.net/2ezhd
  • @Juan “粗略的例子”...
  • @Reigel 你是对的,我以为我很久以前就检查过了......谢谢!
【解决方案2】:

在检查了 Reigels 的想法和 this one 之后,我针对设置 type="file" 输入字段样式的常见问题编写了这个简单的解决方案(在 Firefox、Safari 和 Chrome 上进行了测试)。

<div style="position:relative;">
<div id="file" style="position:absolute;">Click here to select a file</div>
<input type="file" name="file" style="opacity:0; z-index:1;" onchange="document.getElementById('file').innerHTML = this.value;">
</div>

那么您当然可以根据需要设置“文件” div 的样式。

如果您想使用type="text" 输入而不是div,只需将innerHTML 更改为value

<div style="position:relative;">
<input type="text" id="file" style="position:absolute;" placeholder="Click here to select a file">
<input type="file" name="file" style="opacity:0; z-index:1;" onchange="document.getElementById('file').value = this.value;">
</div>

这是我使用 jQuery 的原始答案:

<div style="position:relative;">
<div id="file" style="position:absolute;">Click here to select a file</div>
<input type="file" name="file" style="opacity:0; z-index:1;" onchange="$('#file').text($(this).val());">
</div>

【讨论】:

  • 这种技术的缺点是文件输入仍然呈现为可点击的目标(您看不到)。如果您设置“文件” div 的样式,使其小于隐藏的 ,则您在其周围或其他表单元素周围留下了透明的点击目标。只要您将 div 设置为大于任何浏览器的本机文件元素,它就可以正常工作。
  • 将文件选择元素的宽度和高度设置为其父容器区域的 100%,并且无论浏览器如何呈现本机 gui 元素,都应适当调整其大小。至少,这在最新的 FF、Chrome、Safari 和 IE9/10 中对我有用。
【解决方案3】:

我也为此做了一个自定义样式。看看吧

JS Fiddle Demo - Custom Input type="file"

HTML

<input type="file" id="test">
<div class="button-group"> 
<a href="#" id="browse" class="button primary">Browse</a>
<a href="#" id="save" class="button">Save</a>
<a href="#" id="clear" class="button danger">Clear</a>
</div>
<input type="text" id="testfile"></input>

CSS

body {
padding:100px;
}
input[type="file"] {
position:absolute;
display:none;
}
#testfile {
height: 26px;
text-decoration: none;
background-color: #eee;
border:1px solid #ccc;
border-radius:3px;
float:left;
margin-right:5px;
overflow:hidden;
text-overflow:ellipsis;
color:#aaa;
text-indent:5px;
}
#actionbtnBrowse, #actionbtnSave {
margin:0 !important;
width:60px;
}

JQuery

$("#browse").click(function () {
$("#test").click();
})

$("#save").click(function () {
alert('Run a save function');
})

$("#clear").click(function () {
$('#testfile').val('');
})

$('#test').change(function () {
$('#testfile').val($(this).val());
})

也添加到外部资源标签:

https://github.com/necolas/css3-github-buttons/blob/master/gh-buttons.css

【讨论】:

    【解决方案4】:

    以下是如何使用 HTML、CSS 和 Javascript(不使用任何框架)来实现:

    我们的想法是隐藏&lt;input type='file'&gt; 按钮并使用您将其设置为文件上传按钮的虚拟&lt;div&gt;。点击这个&lt;div&gt;,我们调用隐藏的&lt;input type='file'&gt;

    演示:

    // comments inline
    

    document.getElementById("customButton").addEventListener("click", function(){
      document.getElementById("fileUpload").click();  // trigger the click of actual file upload button
    });
    
    document.getElementById("fileUpload").addEventListener("change", function(){
      var fullPath = document.getElementById('fileUpload').value;
      var fileName = fullPath.split(/(\\|\/)/g).pop();  // fetch the file name
      document.getElementById("fileName").innerHTML = fileName;  // display the file name
    }, false);
    body{
      font-family: Arial;
    }
    
    #fileUpload{
      display: none; /* do not display the actual file upload button */
    }
    
    #customButton{  /* style the dummy upload button */
      background: yellow;
      border: 1px solid red;
      border-radius: 5px;
      padding: 5px;
      display: inline-block;
      cursor: pointer;
      color: red;
    }
    <input type="file" id="fileUpload"> <!-- actual file upload button -->
    <div id="customButton">Browse</div>  <!-- dummy file upload button which can be used for styling ;) -->
    <span id="fileName"></span> <!-- the file name of the selected file will be shown here -->

    【讨论】:

    • 太棒了,太棒了,太棒了,太棒了,太棒了,太棒了,太棒了,太棒了,太棒了,太棒了,太棒了,太棒了,太棒了,太棒了,太棒了。
    【解决方案5】:

    除了雷格尔,

    这里是更简单的实现。您也可以在多个文件输入字段上使用此解决方案。希望这可以帮助一些人;-)

    HTML(单输入)

    <input type="file" name="file" />
    

    HTML(多输入)

    <!-- div is important to separate correctly or work with jQuery's .closest() -->
    <div>
      <input type="file" name="file[]" />
    </div>
    
    <div>
      <input type="file" name="file[]" />
    </div>
    
    <div>
      <input type="file" name="file[]" />
    </div>
    

    JavaScript

    // make all input fields with type 'file' invisible
    $(':file').css({
      'visibility': 'hidden',
      'display': 'none'
    });
    
    // add a textbox after *each* file input
    $(':file').after('<input type="text" readonly="readonly" value="" class="fileChooserText" /> <input type="button" value="Choose file ..." class="fileChooserButton" />');
    
    // add *click* event to *each* pseudo file button
    // to link the click to the *closest* original file input
    $('.fileChooserButton').click(function() {
        $(this).parent().find(':file').click();
    }).show();
    
    // add *change* event to *each* file input
    // to copy the name of the file in the read-only text input field
    $(':file').change(function() {
        $(this).parent().find('.fileChooserText').val($(this).val());
    });
    

    【讨论】:

      【解决方案6】:

      不需要假的 div! 没有 Js 没有额外的 html。仅使用 css 是可能的。

      最好的方法是使用伪元素 :after 或 :before 作为 de 输入的元素。然后根据需要设置该伪元素的样式。我建议您将所有输入文件的一般样式如下:

      input[type="file"]:before {
        content: 'Browse';
        background: #FFF;
        width: 100%;
        height: 35px;
        display: block;
        text-align: left;
        position: relative;
        margin: 0;
        margin: 0 5px;
        left: -6px;
        border: 1px solid #E0E0E0;
        top: -1px;
        line-height: 35px;
        color: #B6B6B6;
        padding-left: 5px;
        display: block;
      }
      

      --> DEMO

      【讨论】:

      • 请@Misha 选择您最喜欢的答案作为正确答案。谢谢
      【解决方案7】:

      这是我使用的一个使用 jQuery 的示例,我已经针对 Firefox 11、Chrome 18 以及 IE9 进行了测试。所以它与我书中的浏览器非常兼容,尽管我只使用这三个。

      HTML

      这是一个基本的“可定制”HTML 结构。

      <span>
          File to Upload<br />
          <label class="smallInput" style="float:left;">
              <input type="file" name="file" class="smallInput" />
          </label>
          <input type="button" class="upload" value="Upload" style="float:left;margin-top:6px;margin-left:10px;" />
      </span>
      

      CSS

      这是我的 CSS 示例

      label.smallInput {
          background:url(images/bg_s_input.gif) no-repeat;
          width:168px;
      }
      

      JavaScript

      这是举重者。

      /* File upload magic form?? */
      $("input.smallInput[type=file]").each(function(i){
          var id      = "__d_file_upload_"+i;
          var d_wrap  = $('<div/>').attr('id',id).css({'position':'relative','cursor':'text'});
      
          $(this).wrap(d_wrap).bind('change blur focus keyup click',function(){
              $("#"+id+" input[type=text]").val($(this).val());
          }).css({'opacity':0,'zIndex':9999,'position':'absolute'}).removeClass('smallInput');
      
          obj = $(this);
      
          $("#"+id).append($("<input/>").addClass('smallInput').attr('type','text').css({'zIndex':9998,'position':'absolute'}).bind('click',function(e){obj.trigger('click');$(this).blur();}));
          obj.closest('span').children('input.upload[type=button]').bind('click',function(e){
              obj.trigger('click');
              $(this).blur();
          });
      });
      /* ************************ */
      

      说明

      HTML 非常简单,只是一个简单的元素,我包含了按钮,因此它可以独立于其他部分命名,当然这可以包含在 JavaScript 中,但简单地说,我有点懒边。该代码使用具有 文件类型smallInput 类搜索所有 输入,这允许您在万一浏览器觉得很痛苦。

      此方法仅使用 JavaScript 来确保传递,它不会改变任何与文件输入有关的浏览器行为。

      您可以修改 HTML 和 JavaScript 以使其非常健壮,此代码足以满足我当前的项目,所以我怀疑我会对其进行任何更改。

      注意事项

      • 不同的浏览器对文件输入值的处理方式不同,这在 chrome 中会导致在 windows 机器上为 c:\fakeroot\。
      • 使用匿名函数(因为没有更好的词),这意味着如果您输入的文件过多,您可能会导致浏览器在处理时运行缓慢。

      【讨论】:

        【解决方案8】:

        今天遇到了同样的问题,但似乎有一个简单的方法来拥有自己的样式 - 隐藏输入,并设置相关标签的样式:

        <div class="upload">
          <label for="my-input"> Upload stuff </label>
          <input type="file" id="my-input" name="files[]" />
        </div>
        

        CSS:

        .upload input{
          display: none;
        }
        
        .upload label{
          background: DarkSlateBlue;
          color: white;
          padding: 5px 10px;
        }
        

        适用于最新的 Chrome、Firefox 和 IE 10。未测试其他版本

        【讨论】:

        • 在 safari 5.1.7 上无法使用,很遗憾,这是一个不错的 hack。
        【解决方案9】:

        虽然 Reigel 的回答传达了这个想法,但它并没有真正附加任何风格。我最近遇到了这个问题,尽管 Stack Overflow 上有很多答案,但似乎没有一个真正符合要求。最后,我最终定制了这个,以获得一个简单而优雅的解决方案。

        我还在 Firefox、IE(11、10 和 9)、Chrome 和 Opera、iPad 和一些安卓设备上进行了测试。

        这是 JSFiddle 链接 -> http://jsfiddle.net/umhva747/

        $('input[type=file]').change(function(e) {
            $in = $(this);
            $in.next().html($in.val());
            
        });
        
        $('.uploadButton').click(function() {
            var fileName = $("#fileUpload").val();
            if (fileName) {
                alert(fileName + " can be uploaded.");
            }
            else {
                alert("Please select a file to upload");
            }
        });
        body {
            background-color:Black;
        }
        
        div.upload {
            background-color:#fff;
            border: 1px solid #ddd;
            border-radius:5px;
            display:inline-block;
            height: 30px;
            padding:3px 40px 3px 3px;
            position:relative;
            width: auto;
        }
        
        div.upload:hover {
            opacity:0.95;
        }
        
        div.upload input[type="file"] {
            display: input-block;
            width: 100%;
            height: 30px;
            opacity: 0;
            cursor:pointer;
            position:absolute;
            left:0;
        }
        .uploadButton {
            background-color: #425F9C;
            border: none;
            border-radius: 3px;
            color: #FFF;
            cursor:pointer;
            display: inline-block;
            height: 30px;
            margin-right:15px;
            width: auto;
            padding:0 20px;
            box-sizing: content-box;
        }
        
        .fileName {
            font-family: Arial;
            font-size:14px;
        }
        
        .upload + .uploadButton {
            height:38px;
        }
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <form action="" method="post" enctype="multipart/form-data">
            <div class="upload">
                <input type="button" class="uploadButton" value="Browse" />
                <input type="file" name="upload" accept="image/*" id="fileUpload" />
                <span class="fileName">Select file..</span>
            </div>
            <input type="button" class="uploadButton" value="Upload File" />
        </form>

        希望对你有帮助!!!

        【讨论】:

          【解决方案10】:

          这是一个带有文本字段的解决方案,用户在其中输入服务器上文件副本的(相对)路径名(如果授权)和一个提交按钮,用于浏览本地系统的文件并发送表单:

          <form enctype="multipart/form-data" action="" method="post">
          <input type="hidden" name="MAX_FILE_SIZE" value="1000000" />
          <p><input type="file" name="upload_file" id="upload_file" size="40"/></p>
          <p><input type="text" id="upload_filename" name="upload_filename" size="30" maxlength="100" value="<?php echo htmlspecialchars($filename, ENT_COMPAT, 'UTF-8'); ?>"/>
          <input type="submit" class="submit submit_upload" id="upload_upload" name="upload_upload" value="Upload"/></p>
          </form>
          

          脚本部分隐藏文件输入,如果用户单击提交按钮,则单击它,如果用户选择了文件,则提交表单。如果用户尝试在不输入文件名的情况下上传文件,则焦点首先会移至文件名的文本字段。

          <script type="text/javascript">
          var file=$('#upload_file');
          var filename=$('#upload_filename');
          var upload=$('#upload_upload');
          
          file.hide().change(function() {if (file.val()) {upload.unbind('click').click();}});
          
          upload.click(function(event) {event.preventDefault();if (!filename.val()) {filename.focus();} else {file.click();}});
          </script>
          

          简单地设置提交按钮的样式以获得完美的结果:

          .submit {padding:0;margin:0;border:none;vertical-align:middle;text-indent:-1000em;cursor:pointer;}
          .submit_upload {width:100px;height:30px;background:transparent url(../images/theme/upload.png) no-repeat;}
          

          【讨论】:

            【解决方案11】:

            如果我明白你的意思,这是我的方法

            HTML

            <form action="upload.php">
                <input type="file" id="FileInput" style="cursor: pointer;  display: none"/>
                <input type="submit" id="Up" style="display: none;" />
            </form>
            

            jQuery

            <script type="text/javascript">
                $( "#FileInput" ).change(function() {
                  $( "#Up" ).click();
                });
            </script>
            

            【讨论】:

              【解决方案12】:

              当您检索输入字段的值时,浏览器将返回一个假路径(在 Chrome 中为 C:\fakepath[filename])。所以我会在 Javascript 解决方案中添加以下内容:

              val=$('#file').val(); //File field value
              
              val=val.replace('/','\\'); //Haven't tested it on Unix, but convert / to \ just in case
              val=val.substring(val.lastIndexOf('\\')+1);
              
              $('#textbox').val(val);
              

              Ofc,它可以在一行中完成。

              【讨论】:

                猜你喜欢
                • 2011-06-17
                • 2013-09-05
                • 2012-02-16
                • 1970-01-01
                • 2021-12-04
                • 2015-07-04
                • 2015-06-17
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多