CSS Twitter Bootstrap 表单文件元素上传按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11235206/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 04:20:18  来源:igfitidea点击:

Twitter Bootstrap Form File Element Upload Button

cssformstwitter-bootstrapinput-type-file

提问by jkushner

Why isn't there a fancy file element upload button for twitter bootstrap? It would be sweet if the blue primary button was implemented for the upload button. Is it even possible to finesse the upload button using CSS? (seems like a native browser element that can't be manipulated)

为什么 twitter bootstrap 没有花哨的文件元素上传按钮?如果为上传按钮实现了蓝色主按钮,那就太好了。甚至可以使用 CSS 优化上传按钮吗?(似乎是无法操作的原生浏览器元素)

回答by claviska

Here's a solution for Bootstrap 3 and 4.

这是 Bootstrap 3 和 4 的解决方案。

To make a functional file input control that looks like a button, you only need HTML:

要制作一个看起来像按钮的功能性文件输入控件,您只需要 HTML:

HTML

HTML

<label class="btn btn-default">
    Browse <input type="file" hidden>
</label>

This works in all modern browsers, including IE9+. If you need support for old IE as well, please use the legacy approach shown below.

这适用于所有现代浏览器,包括 IE9+。如果您还需要对旧 IE 的支持,请使用下面显示的旧方法。

This techniques relies on the HTML5 hiddenattribute. Bootstrap 4 uses the following CSS to shim this feature in unsupportive browsers. You may need to add if you're using Bootstrap 3.

这种技术依赖于 HTML5hidden属性。Bootstrap 4 使用以下 CSS 在不支持的浏览器中填充此功能。如果您使用的是 Bootstrap 3,则可能需要添加。

[hidden] {
  display: none !important;
}


Legacy approach for old IE

旧 IE 的遗留方法

If you need support for IE8 and below, use the following HTML/CSS:

如果您需要对 IE8 及以下的支持,请使用以下 HTML/CSS:

HTML

HTML

<span class="btn btn-default btn-file">
    Browse <input type="file">
</span>

CSS

CSS

.btn-file {
    position: relative;
    overflow: hidden;
}
.btn-file input[type=file] {
    position: absolute;
    top: 0;
    right: 0;
    min-width: 100%;
    min-height: 100%;
    font-size: 100px;
    text-align: right;
    filter: alpha(opacity=0);
    opacity: 0;
    outline: none;
    background: white;
    cursor: inherit;
    display: block;
}

Note that old IE doesn't trigger the file input when you click on a <label>, so the The CSS "bloat" does a couple things to work around that:

请注意,旧的 IE 在您单击 时不会触发文件输入<label>,因此 CSS“膨胀”做了一些事情来解决这个问题:

  • Makes the file input span the full width/height of the surrounding <span>
  • Makes the file input invisible
  • 使文件输入跨越周围的整个宽度/高度 <span>
  • 使文件输入不可见


Feedback & Additional Reading

反馈和补充阅读

I've posted more details about this method, as well as examples for how to show the user which/how many files are selected:

我已经发布了有关此方法的更多详细信息,以及如何向用户显示选择了哪些/多少文件的示例:

http://www.abeautifulsite.net/whipping-file-inputs-into-shape-with-bootstrap-3/

http://www.abeautifulsite.net/whipping-file-inputs-into-shape-with-bootstrap-3/

回答by Kirill Fuchs

Im surprised there was no mention of the <label>element.

我很惊讶没有提到这个<label>元素。

Solution:

解决方案:

<label class="btn btn-primary" for="my-file-selector">
    <input id="my-file-selector" type="file" class="d-none">
    Button Text Here
</label>

No need for any JS, or funky css...

不需要任何 JS 或时髦的 css ......

Solution for including the filename:

包含文件名的解决方案:

<label class="btn btn-primary" for="my-file-selector">
    <input id="my-file-selector" type="file" style="display:none" 
    onchange="$('#upload-file-info').html(this.files[0].name)">
    Button Text Here
</label>
<span class='label label-info' id="upload-file-info"></span>

The solution above requires jQuery.

上面的解决方案需要jQuery。

回答by codefreak

With no additional plugin required, this bootstrap solution works great for me:

不需要额外的插件,这个引导解决方案对我来说非常有用:

<div style="position:relative;">
        <a class='btn btn-primary' href='javascript:;'>
            Choose File...
            <input type="file" style='position:absolute;z-index:2;top:0;left:0;filter: alpha(opacity=0);-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";opacity:0;background-color:transparent;color:transparent;' name="file_source" size="40"  onchange='$("#upload-file-info").html($(this).val());'>
        </a>
        &nbsp;
        <span class='label label-info' id="upload-file-info"></span>
</div>

demo:

演示:

http://jsfiddle.net/haisumbhatti/cAXFA/1/(bootstrap 2)

http://jsfiddle.net/haisumbhatti/cAXFA/1/(引导程序 2)

enter image description here

在此处输入图片说明

http://jsfiddle.net/haisumbhatti/y3xyU/(bootstrap 3)

http://jsfiddle.net/haisumbhatti/y3xyU/(引导程序 3)

enter image description here

在此处输入图片说明

回答by Arnold Daniels

It's included in Jasny's fork of bootstrap.

它包含在 Jasny 的引导程序分支中。

A simple upload button can be created using

可以使用创建一个简单的上传按钮

<span class="btn btn-file">Upload<input type="file" /></span>

With the fileupload plugin you can create more advanced widgets. Have a look at http://jasny.github.io/bootstrap/javascript/#fileinput

使用文件上传插件,您可以创建更高级的小部件。看看 http://jasny.github.io/bootstrap/javascript/#fileinput

回答by baptme

Upload buttons are a pain to style because it styles the input and not the button.

上传按钮的样式很麻烦,因为它设置了输入的样式而不是按钮的样式。

but you can use this trick:

但你可以使用这个技巧:

http://www.quirksmode.org/dom/inputfile.html

http://www.quirksmode.org/dom/inputfile.html

Summary:

概括:

  1. Take a normal <input type="file">and put it in an element with position: relative.

  2. To this same parent element, add a normal <input>and an image, which have the correct styles. Position these elements absolutely, so that they occupy the same place as the <input type="file">.

  3. Set the z-index of the <input type="file">to 2 so that it lies on top of the styled input/image.

  4. Finally, set the opacity of the <input type="file">to 0. The <input type="file">now becomes effectively invisible, and the styles input/image shines through, but you can still click on the "Browse" button. If the button is positioned on top of the image, the user appears to click on the image and gets the normal file selection window. (Note that you can't use visibility: hidden, because a truly invisible element is unclickable, too, and we need the to remain clickable)

  1. 取一个法线<input type="file">并将其放入带有position: relative.

  2. 向同一个父元素添加<input>具有正确样式的法线和图像。绝对定位这些元素,使它们与<input type="file">.

  3. 将 的 z-index 设置<input type="file">为 2,使其位于样式化输入/图像的顶部。

  4. 最后,将 的不透明度设置<input type="file">为 0。<input type="file">现在实际上是不可见的,样式输入/图像会透过,但您仍然可以单击“浏览”按钮。如果按钮位于图像顶部,则用户似乎单击图像并获得正常的文件选择窗口。(请注意,您不能使用可见性:隐藏,因为真正不可见的元素也是不可点击的,我们需要保持可点击)

回答by fguillen

Works for me:

对我有用:

Update

更新

jQuery plugin style:

jQuery 插件风格

// Based in: http://duckranger.com/2012/06/pretty-file-input-field-in-bootstrap/
// Version: 0.0.3
// Compatibility with: Bootstrap 3.2.0 and jQuery 2.1.1
// Use:
//     <input class="nice_file_field" type="file" data-label="Choose Document">
//     <script> $(".nice_file_field").niceFileField(); </script>
//
(function( $ ) {
  $.fn.niceFileField = function() {
    this.each(function(index, file_field) {
      file_field = $(file_field);
      var label = file_field.attr("data-label") || "Choose File";

      file_field.css({"display": "none"});

      nice_file_block_text  = '<div class="input-group nice_file_block">';
      nice_file_block_text += '  <input type="text" class="form-control">';
      nice_file_block_text += '  <span class="input-group-btn">';
      nice_file_block_text += '   <button class="btn btn-default nice_file_field_button" type="button">' + label + '</button>';
      nice_file_block_text += '  </span>';
      nice_file_block_text += '</div>';

      file_field.after(nice_file_block_text);

      var nice_file_field_button = file_field.parent().find(".nice_file_field_button");
      var nice_file_block_element = file_field.parent().find(".nice_file_block");

      nice_file_field_button.on("click", function(){ console.log("click"); file_field.click() } );
      file_field.change( function(){
        nice_file_block_element.find("input").val(file_field.val());
      });
    });
  };
})( jQuery );

回答by mindriot

Simplified answer using parts from other answers, primarily user2309766 and dotcomsuperstar.

使用其他答案的部分简化答案,主要是 user2309766 和 dotcomsuperstar。

Features:

特征:

  • Uses Bootstrap button addon for button and field.
  • Only one input; multiple inputs would be picked up by a form.
  • No extra css except "display: none;" to hide the file input.
  • Visible button fires click event for hidden file input.
  • splitto remove file path uses regex and delimiters '\' and '/'.
  • 对按钮和字段使用 Bootstrap 按钮插件。
  • 只有一个输入;多个输入将被一个表单接收。
  • 除了 "display: none;" 没有额外的 css 隐藏文件输入。
  • 可见按钮触发隐藏文件输入的点击事件。
  • split删除文件路径使用正则表达式和分隔符“\”和“/”。

Code:

代码:

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="input-group">
  <span class="input-group-btn">
    <span class="btn btn-primary" onclick="$(this).parent().find('input[type=file]').click();">Browse</span>
    <input name="uploaded_file" onchange="$(this).parent().parent().find('.form-control').html($(this).val().split(/[\|/]/).pop());" style="display: none;" type="file">
  </span>
  <span class="form-control"></span>
</div>

回答by dotcomly

With some inspiration from other posts above, here is a full solution that combines what looks like a form-control field with an input-group-addon for a clean file input widget that includes a link to the current file.

从上面的其他帖子中获得一些灵感,这里有一个完整的解决方案,它将看起来像表单控件字段的内容与输入组插件相结合,用于包含指向当前文件的链接的干净文件输入小部件。

.input-file { position: relative; margin: 60px 60px 0 } /* Remove margin, it is just for stackoverflow viewing */
.input-file .input-group-addon { border: 0px; padding: 0px; }
.input-file .input-group-addon .btn { border-radius: 0 4px 4px 0 }
.input-file .input-group-addon input { cursor: pointer; position:absolute; width: 72px; z-index:2;top:0;right:0;filter: alpha(opacity=0);-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";opacity:0; background-color:transparent; color:transparent; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
<div class="input-group input-file">
  <div class="form-control">
    <a href="/path/to/your/current_file_name.pdf" target="_blank">current_file_name.pdf</a>
  </div>
  <span class="input-group-addon">
    <a class='btn btn-primary' href='javascript:;'>
      Browse
      <input type="file" name="field_name" onchange="$(this).parent().parent().parent().find('.form-control').html($(this).val());">
    </a>
  </span>
</div>

回答by monsur.hoq

Please check out Twitter Bootstrap File Input. It use very simple solution, just add one javascript file and and paste following code:

请查看Twitter Bootstrap 文件输入。它使用非常简单的解决方案,只需添加一个 javascript 文件并粘贴以下代码:

$('input[type=file]').bootstrapFileInput();

回答by MoBKK

This works perfectly for me

这对我来说非常有效

<span>
    <input  type="file" 
            style="visibility:hidden; width: 1px;" 
            id='${multipartFilePath}' name='${multipartFilePath}'  
            onchange="$(this).parent().find('span').html($(this).val().replace('C:\fakepath\', ''))"  /> <!-- Chrome security returns 'C:\fakepath\'  -->
    <input class="btn btn-primary" type="button" value="Upload File.." onclick="$(this).parent().find('input[type=file]').click();"/> <!-- on button click fire the file click event -->
    &nbsp;
    <span  class="badge badge-important" ></span>
</span>