使用 CSS 和一点 JS 设置输入类型文件的样式,可以吗

Styling the input type file with CSS and a little JS, is this ok?

本文关键字:文件 类型 样式 输入 设置 CSS JS 一点 使用      更新时间:2023-09-26

我要做的是添加一个用于向上移动文件的按钮,我可以设置该按钮并显示所选文件的名称。

搜索了很多,我搜索得越多,我找到的不同解决方案就越多。我发现,你不能直接设置输入的样式,因为你就是不能......:(。

最后,我从每个解决方案中挑选了一些,得出以下几点:

我在标签中为输入[类型文件]设置了一个范围,并通过显示:none;隐藏了输入。

现在,我可以根据自己的需要设置跨度的样式,并在单击时调用输入。最后使用小JS,获取输入的值(拾取文件的名称(并显示它,而不是样式按钮上的跨度文本。

但看看你自己:

#input-file {
    display: none;
    }
.upload-btn {
    display: block;
    text-align: center;
    margin: 20px auto 20px;
    width: 50%;
    height: 30px;
    background-color: #fcff7f;
    line-height: 30px;
    }
.upload-btn:hover {
    background-color: #c39d5a;
    color: white;
    cursor: pointer;
    }
<label class="upload-btn">
  <input type="file" id="input-file" onchange="changeText()" />
  <span id="selectedFileName">Browse</span>
</label>

<script type="text/javascript">
  function changeText() {
    var y = document.getElementById("input-file").value;
    document.getElementById("selectedFileName").innerHTML = y;
  }
</script>

我想知道的是,这有什么问题?就我的理解而言,这非常简单,如此简单,以至于我不明白为什么我在互联网上找到的所有解决方案都更加困难。他们都试图使用虚假输入,不透明等等。

所以请一个非常有经验的人告诉我是否可以这样使用它,或者我必须改变它?为了什么?

谢谢;)还有很多英语不好的借口。

由于安全原因,此功能在浏览器中不可用。

查看此解释: https://stackoverflow.com/a/15201258/586051

只有火狐浏览器允许它。请参考 Firefox 中的以下示例。

编辑:您可以通过以下方式获取所选文件的文件名:

EDIT2:以下代码片段演示了文件上传按钮的样式。在这里,我们实际上是在伪造它,但最终用户不会知道它。;)

编辑3:注释中fullPath的附加值。

编辑4:在HTML中添加<div>包装器

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 = this.value; // fetched value = C:'fakepath'fileName.extension
  var fileName = fullPath.split(/(''|'/)/g).pop();  // fetch the file name
  document.getElementById("fileName").innerHTML = fileName;  // display the file name
}, false);
#fileUpload{
  display: none; /* do not display the actual file upload button */
}
#customButton{  /* style the fake upload button */
  background: yellow;
  border: 1px solid red;
}
<div>
  <input type="file" id="fileUpload"> <!-- actual file upload button -->
  <button id="customButton">My Custom Button</button>  <!-- fake file upload button which can be used for styling ;) -->
  <span id="fileName"></span>
</div>