html - 现代浏览器中的样式输入类型 "file"

标签 html css input

<分区>

我想问一下如何在 2019 年设置输入字段 type='file' 的样式?我看到很多问题和答案,但几乎所有问题和答案都需要 jQuery,而且我们知道 jQuery 不像 10 年前那样流行。我想添加一些图标作为按钮,我知道有很多库可以为您带来完整的输入字段,但这不是我想做的重点,但我想学习如何自定义和设置我自己的输入字段类型='文件'。

Styling an input type="file" button

enter image description here

如何在输入字段中显示 2019 年正在更新的文件?

最佳答案

正如我在评论部分所说,您需要一个 label 标记以及一些 CSS 来实现这一目的。事实上,您需要 JavaScript 来为您的UI 注入(inject)活力。

所以,我在这里为您制作一个演示:

const inputFile = document.querySelector('.my-file'),
  label = document.querySelector('.custom-input'),
  icon = label.querySelector('.label-icon'),
  text = label.querySelector('.label-text');
inputFile.addEventListener('change', () => {
  text.textContent = 'Please, choose a file.';
  if (inputFile.files.length === 1) {
    text.textContent = inputFile.files[0].name.toUpperCase();
    text.classList.add('attached');
    icon.classList.add('attached');
  } else {
    text.classList.remove('attached');
    icon.classList.remove('attached');
  }
});
.container {
  padding: 12px 6px;
  background-color: #f6f6f6;
}

.wrapper {
  display: flex;
  justify-content: flex-start;
  align-items: stretch;
  border: 1px solid #dedede;
  border-radius: 6px;
  overflow: hidden;
}

.wrapper .my-file {
  display: none;
}

.wrapper .custom-input {
  background-color: #fff;
  flex: 1;
  cursor: pointer;
}

.wrapper .custom-input .label-icon {
  display: inline-block;
  padding: 15px;
  background-color: #fde4af;
  color: #181818;
  transition: all .4s 0s ease;
}

.wrapper .custom-input .label-icon.attached {
  background-color: #e6ac2d;
  color: #fff;
}

.wrapper .custom-input .label-icon.attached > .fa {
  text-shadow: 0 0 15px rgba(24, 24, 24, .35);
}

.wrapper .custom-input .label-text {
  display: inline-block;
  padding: 4px;
  transition: all .4s 0s ease;
}

.wrapper .custom-input .label-text.attached {
  font-weight: 600;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.9.0/css/all.min.css" />
<div class="container">
  <form action="#" id="my-form">
    <div class="wrapper">
      <input type="file" id="my-file" name="my-file" class="my-file" />
      <label for="my-file" class="custom-input">
      <span class="label-icon">
        <i class="fa fa-folder"></i>
      </span>
      <span class="label-text">Please, choose a file.</span>
    </label>
    </div>
  </form>
</div>

希望我能进一步插入您,并在此等待进一步的解释。

关于html - 现代浏览器中的样式输入类型 "file",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56906913/

上一篇:javascript - Angular Material 设计 : Radio button group to be vertically aligned

下一篇:html - 为什么这个 CSS 动画在 IE 上不起作用?

相关文章:

html - 使用 CSS 保持 div 的纵横比

python - 如何拆分Python中同一行的一些信息?

c++ - 如何检查数组输入是否失败?

javascript - 更改 <img> 的 src 属性并在加载时显示新图像

javascript - 使用 javascript 更改多个不同的类

html - 导航菜单对齐

css - 构建 CSS 样式表的最佳方式

python - 将多行(读取为单行/输入)粘贴到 Spyder 控制台

jquery - HTML 表到 JSON

javascript - 如何使用 jquery 创建带导航按钮的幻灯片