【问题标题】:CSS selector for empty file input空文件输入的 CSS 选择器
【发布时间】:2018-02-08 21:07:51
【问题描述】:

我知道样式文件输入非常少,这不是一件坏事。

有什么方法可以选择空的文件输入吗?

计划是根据文件输入是否为空来显示或隐藏提交按钮。

【问题讨论】:

  • 没有 JavaScript element.files 你不能
  • 你应该使用 Javascript 来做这样的事情。
  • 是的,我错误地删除了第二行中的“那里”。但是没有必要在你的问题前加上防止任何人说你不能输入样式元素 - 众所周知,它们可以被设置样式,所以如果有人知道一点,他们根本不应该回答,可以忽略: )
  • @MoisheLipsker 是的,不是的——我无法让它为我工作,所以没有,但如果它有效,那么是的。
  • 很多人说你不能用 CSS 做到这一点,然后看到接受的答案是纯 CSS 解决方案,我很困惑¯_(ツ)_/¯

标签: html css css-selectors forms


【解决方案1】:

如果您愿意将input 标记为required、you could do it with just css:

input:invalid ~ .chosen {
    display: none;
}
input:valid ~ .empty {
    display: none;
}
<input type="file" required><br>

<span class="empty">Empty</span>
<span class="chosen">Chosen</span>

【讨论】:

  • 这是一个非常好的方法。关键是在您提交之前需要该文件,这就是为什么我想隐藏它。谢谢
  • 布里尔扬兹。喜欢required 的触摸。
【解决方案2】:

有什么方法可以选择空的文件输入吗?

没有。

您将需要 JavaScript。您可以在 SO 和其他地方找到几个答案。基本思想是观察change事件的元素,添加一个类如non-empty表示有文件被选中,然后样式input[type="file"].non-empty + label,假设您使用使用label作为替换文件的技术输入按钮。您将不得不特例 form.reset() 清空表单内的文件输入,但不会在输入上触发 change 事件。这是一些示例代码(没有form.reset 部分):

// Add a class to a file input if it's not empty.
function mark() { this.classList.toggle('non-empty', this.files.length); }

// Watch a file input and update non-empty status.
function watch(input) { input.addEventListener('change', mark); }

// Get all file inputs.
const inputs = Array.from(document.querySelectorAll('input[type=file]'));

// Watch all file inputs in the whole document.
inputs . forEach(watch);
input[type="file"]                          { width: 0.1px; height: 0.1px; }
input[type="file"].non-empty + label        { color: green; }
input[type="file"].non-empty + label::after { content: ' (specified)'; }
<input type="file" id="input">
<label for="input">Specify file</label>

【讨论】:

  • 0.1px 的尺寸让我很感兴趣。是否有任何浏览器无法通过 display: none 提交文件输入?
  • @BoltClock 显然,是的,至少根据我曾经在某处看到的东西。
猜你喜欢
  • 2011-05-06
  • 2017-11-21
  • 2013-08-07
  • 1970-01-01
  • 2011-04-15
  • 2015-10-01
  • 2013-06-22
  • 2020-03-20
  • 1970-01-01
相关资源
最近更新 更多