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

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


当前回答

我能想到的唯一方法是在它被渲染后用javascript找到按钮,并分配一个样式给它

你也可以看看这个记录

其他回答

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

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

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

最好的方法是使用伪元素:after或:before作为显化de input的元素。然后按照您的意愿设置该伪元素的样式。我建议你为所有输入文件做一个通用的样式,如下所示:

input {
  height: 0px;
  outline: none;
}

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

如果你正在使用Bootstrap 3,这对我来说是有效的:

参见https://www.abeautifulsite.net/posts/whipping-file-inputs-into-shape-with-bootstrap-3/

.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; } <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" /> <span class="btn btn-primary btn-file"> Browse...<input type="file"> </span>

它会产生以下文件输入按钮:

认真的,去https://www.abeautifulsite.net/posts/whipping-file-inputs-into-shape-with-bootstrap-3/看看吧

你不需要JavaScript !下面是一个跨浏览器的解决方案:

请看这个例子!-适用于Chrome/FF/IE - (IE10/9/8/7)

最好的方法是将一个带有for属性的自定义标签元素附加到隐藏的文件输入元素。(标签的for属性必须匹配文件元素的id,这样才能工作)。

<label for="file-upload" class="custom-file-upload">
    Custom Upload
</label>
<input id="file-upload" type="file"/>

作为一种替代方法,你也可以直接用标签包装文件输入元素:

<label class="custom-file-upload">
    <input type="file"/>
    Custom Upload
</label>

在样式方面,只需使用属性选择器隐藏输入元素。

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

然后,您所需要做的就是设置自定义标签元素的样式。(例子)。

.custom-file-upload {
    border: 1px solid #ccc;
    display: inline-block;
    padding: 6px 12px;
    cursor: pointer;
}

1 -值得注意的是,如果你使用display: none隐藏元素,它将在IE8及以下版本中不起作用。还要注意,jQuery验证默认情况下不验证隐藏字段。如果这两种情况对您来说是一个问题,这里有两种不同的方法来隐藏输入(1,2),在这种情况下可以工作。

如果你正在寻找一个javascript库开箱即用的解决方案,jquery-fileinput工作得很好。