CSS: 如何隐藏文件上传框但保留文件名?

7
我想隐藏文件选择的“选择文件”按钮,但是我想保留文件名。我该怎么做? enter image description here
<input
  name="upload"
  id="upload-input"
  placeholder="Select a file"
  ref="fileInput"
  type="file"
  required>

这不是标记为JavaScript的 - 这可以接受吗?如果可以,这个问题已经被问过/回答过了:https://dev59.com/ipTfa4cB1Zd3GeqPVcbR - random_user_name
6个回答

3
你可以将文件名保存到另一个HTML元素中,然后像这样隐藏选择文件输入框。

function getFileName()
{
var x = document.getElementById('upload-input')
x.style.visibility = 'collapse'
document.getElementById('fileName').innerHTML = x.value.split('\\').pop()
}
<input
  name="upload"
  id="upload-input"
  placeholder="Select a file"
  ref="fileInput"
  type="file"
  required 
  onchange="getFileName()"><span id="fileName"></span>


1
你可以使用 x.value.split('\').pop() 来获取文件名,而不是路径。 - JasonB
OP没有将问题标记为JavaScript...你的解决方案需要JavaScript...值得澄清的是,如果JavaScript可行,以及/或者是否可能/不可能使用纯HTML/CSS。 - random_user_name
此外,如果JS是答案,那么应该将其关闭为重复问题(https://dev59.com/ipTfa4cB1Zd3GeqPVcbR),而不是发布新答案。 - random_user_name

2
只需使用以下CSS:
::-webkit-file-upload-button,
::file-selector-button {
  display: none;
}

::-webkit-file-upload-button,
::file-selector-button {
  display: none;
}
<input type="file">


我认为这是正确的答案。你能添加一个示例片段来证明吗? - undefined
1
我刚刚添加了一小段。 - undefined

1
以下方法对我有效:

input[type="file"] {
    width: 280px;
    line-height: normal;
    height: 32px;
    /* display: none; */
}
input::-webkit-file-upload-button,
input::file-selector-button {
  width:0px;
  overflow:hidden;
  content:"";
  padding: 0;
  font-size: 0;
  border:none;
  height: 40px;
  box-shadow: none;
  align-items: center;
  align-self: center;
  align-content: center;
}
<input type="file"">

它基本上隐藏了按钮,但文件名仍然可以点击。

0
在该位置添加一个新组件:
 <span id='upload-file-name'></span>

使用JavaScript,首先获取文件名

var em = document.getElementById("upload-input");
var fname = em.name;

隐藏文件上传输入框。
em.style.display = 'none';

将文件名放入这个新组件中

document.getElementById("upload-file-name").innerHTML = fname;

OP没有将问题标记为JavaScript...您的解决方案需要JavaScript...可能值得澄清是否可以使用JavaScript,以及/或者是否可以/不可以使用纯HTML/CSS。 - random_user_name
此外,如果JS是答案,那么应该将其关闭为重复问题(https://dev59.com/ipTfa4cB1Zd3GeqPVcbR),而不是发布新答案。 - random_user_name
@cale_b OP没有对任何可能性进行限制。 - ild flue
绝对正确,标签表示所需的技术。这就是标签的作用。您不会在标记为Ruby的问题中发布PHP答案... - random_user_name

0
你可以创建一个div,在选择文件后显示文件名。然后,用display none隐藏你的文件输入框。
所以使用jQuery或JavaScript的onchange或onclick事件来实现。

0

你可以在CSS中使用颜色属性和透明度来隐藏文件名的字母,但按钮不知道。

.inputfile{
  opacity: 0;
}
<input
  name="upload"
  id="upload-input"
  placeholder="Select a file"
  ref="fileInput"
  type="file"
  class="inputfile"
  required>

如果你想要隐藏它,你必须加上:display: none; 但是这样会使得所有东西都被隐藏,无法使用。但是如果你想通过调节透明度和调整输入来让它不可见,那么这可能对你有用。但是如果你想要隐藏按钮和字母,你不能加上color: "任何颜色"。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接