如何使用 CSS3 / Javascript 设置“输入文件”的样式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3226167/
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-23 03:45:54  来源:igfitidea点击:

How to style "input file" with CSS3 / Javascript?

javascriptjqueryhtmlcssfile-io

提问by Misha Moroshko

I would like to style <input type="file" />using CSS3.

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

Alternatively, I would like user to press on a div(that I will style) and this will open the Browse window.

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

Is that possible to do that using HTML, CSS3, and Javascript / jQuery only ?

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

回答by Reigel

I have this rough example that you might want to get some idea...

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

html?

html?

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

CSS

CSS

#file {
    display:none;
}?

jQuery

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

演示

??????????????

???????????????

回答by Sophivorus

After checking Reigels idea, and this one, I wrote this simple solution to the common problem of styling a type="file"input field (tested it on Firefox, Safari and Chrome).

在检查了 Reigels 的想法和这个想法之后,我编写了这个简单的解决方案来解决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>

Then you can of course style the "file" div as you want.

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

And if you want to use a type="text"input instead of a div, simply change innerHTMLfor value:

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

<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>

Here is my original answer using jQuery:

这是我使用 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>

回答by andibra

I made a custom style for this as well. Check it out

我也为此做了一个自定义样式。一探究竟

JS Fiddle Demo - Custom Input type="file"

JS Fiddle 演示 - 自定义输入类型="文件"

HTML

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

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());
})

Also add to external resources tab:

还添加到外部资源选项卡:

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

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

回答by Rahul Desai

Here is how to do it using HTML, CSS and Javascript (without any frameworks):

以下是使用 HTML、CSS 和 Javascript(不使用任何框架)的方法:

The idea is to have the <input type='file'>button hidden and use a dummy <div>that you style as a file upload button. On click of this <div>, we call the hidden <input type='file'>.

这个想法是<input type='file'>隐藏按钮并使用<div>您设计为文件上传按钮的虚拟对象。单击此按钮<div>,我们将其称为 hidden <input type='file'>

Demo:

演示:

// 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 -->

回答by Despertaweb

The fake div is not needed!No Js no extra html. Using only css is possible.

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

The best way is using the pseudo element :after or :before as an element overt the de input. Then style that pseudo element as you wish. I recomend you to do as a general style for all input files as follows:

最好的方法是使用伪元素 :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

--> 演示

回答by Patrick Hillert

In addition of Reigel,

除了雷格尔,

here is more simpler implementation. You can use this solution on multiple file input fields, too. Hope this helps some people ;-)

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

HTML (single input)

HTML(单一输入)

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

HTML (multiple input)

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

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());
});

回答by Satwik Nadkarny

While Reigel's answer conveys the idea, it doesn't really have any style attached to it. I came across this problem recently and despite the plethora of answers on Stack Overflow, none really seemed to fit the bill. In the end, I ended up customizing this so as to have a simple and an elegant solution.

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

I have also tested this on Firefox, IE (11, 10 & 9), Chrome and Opera, iPad and a few android devices.

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

Here's the JSFiddle link -> http://jsfiddle.net/umhva747/

这是 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>

Hope this helps!!!

希望这可以帮助!!!

回答by nice ass

Ran into the same issue today, but it seems there's an easy way to have your own styles - hide the input, and style the associated label:

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

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

CSS:

CSS:

.upload input{
  display: none;
}

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

Works in latest Chrome, Firefox and IE 10. Didn't test others

适用于最新的 Chrome、Firefox 和 IE 10。没有测试其他人

回答by Destreyf

Here's an example that I'm using that utilizes jQuery, I've tested against Firefox 11, and Chrome 18, as well as IE9. So its pretty compatible with browsers in my book, though i only work with those three.

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

HTML

HTML

Here's a basic "Customizable" HTML structure.

这是一个基本的“可定制”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

Here's a sample of my CSS

这是我的 CSS 示例

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

JavaScript

JavaScript

This is the heavy lifter.

这是举重运动员。

/* 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();
    });
});
/* ************************ */

Explanation

解释

The HTML is pretty straight forward, just a simple element, i include the button so it can be named independently from the rest, sure this could be included in the JavaScript, but simply put, I'm a bit on the lazy side. The code searches for all inputswith a class of smallInputthat have the type of filethis allows you to define default HTML and fallback form structure in case a browser decides to be a pain.

HTML 非常简单,只是一个简单的元素,我包含了按钮,因此它可以独立于其余部分命名,当然这可以包含在 JavaScript 中,但简单地说,我有点懒惰。该代码搜索所有投入使用的一类smallInput是有文件的类型,这允许您定义默认的HTML和的情况下,浏览器决定是一个痛苦后备形式结构。

This method only uses JavaScript to ensure delivery, it does not alter any browser behaviors in regards to the file input.

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

You can modify the HTML and JavaScript to make it very robust, this code suffices my current project so i doubt I'll be making any changes to it.

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

Caveats

注意事项

  • Different browsers treat the value of the file input differently, which in chrome results in c:\fakeroot\ on windows machines.
  • Uses anonymous functions, (for lack of a better word) which means if you have too many file inputs you can cause the browser to behave slowly on processing.
  • 不同的浏览器对文件输入的值有不同的处理方式,这在 chrome 中会导致 windows 机器上的 c:\fakeroot\。
  • 使用匿名函数,(因为没有更好的词)这意味着如果您有太多的文件输入,您可能会导致浏览器在处理时表现缓慢。

回答by frasq

Here is a solution with a text field where the user types in the (relative) pathname of the file copy on the server (if authorized) and a submit button to browse the local system for a file and send the form:

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

<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>

The scripting part hides the file input, clicks it if the user clicks on the submit button, submits the form if the user has picked up a file. If the user tries to upload a file without entering a filename, the focus is first moved to the text field for the filename.

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

<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>

Simply style the submit button for a perfect result:

只需设置提交按钮即可获得完美结果:

.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;}