你如何风格输入类型=“文件”按钮?

<输入类型=“文件” />


当前回答

把上传文件按钮放在你漂亮的按钮或元素上并隐藏它。

非常简单,可以在任何浏览器上工作

<div class="upload-wrap">
    <button type="button" class="nice-button">upload_file</button>
    <input type="file" name="file" class="upload-btn">
</div>

风格

.upload-wrap {
    position: relative;
}

.upload-btn {
    position: absolute;
    left: 0;
    opacity: 0;
}

其他回答

这是简单的jquery。对Ryan的建议稍加修改后给出一个代码示例。

基本的html:

<div id="image_icon"></div>
<div id="filename"></div>
<input id="the_real_file_input" name="foobar" type="file">

当你准备好时,一定要在输入上设置样式:不透明度:0 你不能设置display: none,因为它需要是可点击的。但是你可以把它放在“new”按钮下面,或者如果你喜欢的话,把它塞进z-index的其他东西下面。

设置一些jquery,当你点击图像时,点击真正的输入。

$('#image_icon').click(function() {
    $('#the_real_file_input').click();
});

现在你的按钮开始工作了。更改时只需剪切并粘贴值。

$('input[type=file]').bind('change', function() {
    var str = "";
    str = $(this).val();
    $("#filename").text(str);
}).change();

发长音!您可能需要将val()解析为更有意义的内容,但您应该已经全部设置好了。

下面是一个解决方案,它还显示了所选的文件名: http://jsfiddle.net/raft9pg0/1/

HTML:

<label for="file-upload" class="custom-file-upload">Chose file</label>
<input id="file-upload" type="file"/>
File: <span id="file-upload-value">-</span>

JS:

$(function() {
    $("input:file[id=file-upload]").change(function() {
        $("#file-upload-value").html( $(this).val() );
    });
});

CSS:

input[type="file"] {
    display: none;
}

.custom-file-upload {
      background: #ddd;
      border: 1px solid #aaa;
      border-top: 1px solid #ccc;
      border-left: 1px solid #ccc;
      -moz-border-radius: 3px;
      -webkit-border-radius: 3px;
      border-radius: 3px;
      color: #444;
      display: inline-block;
      font-size: 11px;
      font-weight: bold;
      text-decoration: none;
      text-shadow: 0 1px rgba(255, 255, 255, .75);
      cursor: pointer;
      margin-bottom: 20px;
      line-height: normal;
      padding: 8px 10px; }

你可以创建一个很棒的(未完成的)文件上传器到<button>元素或任何其他元素:

函数selectFile() { . getelementbyid (fileSelector) .click (); } 输入# fileSelector (type = "文件"){ 显示:没有; } 按钮onclick * =”()”){ 光标:指针; } <input type="file" id="fileSelector"> <按钮onclick = " selectFile ()>选择文件从计算机

当点击有样式的<div>时,只需使用trigger()函数模拟点击<input>。我在<div>中创建了自己的按钮,然后在点击我的<div>时触发了输入上的单击。这允许你创建你想要的按钮,因为它是一个<div>,模拟点击你的文件<input>。然后在<input>上使用display: none。

// div styled as my load file button
<div id="simClick">Load from backup</div>

<input type="file" id="readFile" />

// Click function for input
$("#readFile").click(function() {
    readFile();
});

// Simulate click on the input when clicking div
$("#simClick").click(function() {
    $("#readFile").trigger("click");
});
 <label>
    <input type="file" />
 </label>

您可以将input type="file"包装在输入的标签中。样式标签,无论你喜欢和隐藏输入display: none;