发布于 2026-01-06 1 阅读
0

像个大佬一样设置样式文件输入

像个大佬一样设置样式文件输入

HTML元素默认样式由各个浏览器应用。这些样式可能因浏览器而异,应用自定义样式的难易程度也可能从非常容易到极其复杂(有时甚至不可能)不等。

在本文中,我们将介绍如何设置文件输入框的样式,文件输入框恰好是使用 CSS 设置样式比较困难的元素之一。

如果你在应用程序中使用过文件输入功能,就会知道默认样式看起来并不美观。如果你想知道它在 Chrome 和 Firefox 中的显示效果,这里有一个示例。

Firefox 和 Chrome 中的默认文件输入框

好消息是,我们可以解决这个问题……坏消息是我们无法使用“传统”方法。

样式文件输入

让我们在 HTML 中创建一个简单的文件输入框。

<div class="file-input">
  <input type="file" id="file" class="file">
  <label for="file">Select file</label>
</div>
Enter fullscreen mode Exit fullscreen mode

要设置文件输入框的样式,首先需要做的就是去掉默认的文件输入框。

隐藏输入框

.file {
  opacity: 0;
  width: 0.1px;
  height: 0.1px;
  position: absolute;
}
Enter fullscreen mode Exit fullscreen mode

你可能会想,为什么不直接display: none隐藏输入框呢?但这样做的问题在于,输入框会从布局中移除,导致使用屏幕阅读器的人无法访问,这会非常糟糕。

另一点需要注意的是label,对于文件输入框,点击标签也会打开文件选择器,因此我们可以利用这一点,随意设置标签样式。

标签设计

现在我们已经隐藏了默认输入框,可以随意设置标签的样式了。为了简单起见,我们先把它设置成按钮的样子。

.file-input label {
  display: block;
  position: relative;
  width: 200px;
  height: 50px;
  border-radius: 25px;
  background: linear-gradient(40deg, #ff6ec4, #7873f5);
  box-shadow: 0 4px 7px rgba(0, 0, 0, 0.4);
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-weight: bold;
  cursor: pointer;
  transition: transform .2s ease-out;
}
Enter fullscreen mode Exit fullscreen mode

带有紫色渐变的样式输入框

无障碍

我们已经成功地将标签样式设置为按钮样式,但这还不够。我们需要为标签添加一些指示,以便在用户将鼠标悬停在字段上或尝试使用键盘聚焦文件字段时显示相应的内容。我在这里做一个简单的处理,当这种情况发生时,增大标签的尺寸。

input:hover + label,
input:focus + label {
  transform: scale(1.02);
}
Enter fullscreen mode Exit fullscreen mode

我们还可以选择在聚焦时为标签添加轮廓。

input:focus + label {
  outline: 1px solid #000;
  outline: -webkit-focus-ring-color auto 2px;
}
Enter fullscreen mode Exit fullscreen mode

-webkit-focus-ring-color属性用于在 Chrome 或 Safari 等 Webkit 内核浏览器上实现默认轮廓效果。对于非 Webkit 内核浏览器,元素将应用黑色轮廓。

Javascript增强功能

我们可以使用 JavaScript 来显示所选文件的名称和大小。这样可以让自定义字段看起来更自然一些。所以,让我们稍微修改一下 HTML 和 CSS 代码。

<div class="file-input">
  <input type="file" id="file" class="file">
  <label for="file">
    Select file
    <p class="file-name"></p>
  </label>
</div>
Enter fullscreen mode Exit fullscreen mode
.file-name {
  position: absolute;
  bottom: -35px;
  left: 10px;
  font-size: 0.85rem;
  color: #555;
}
Enter fullscreen mode Exit fullscreen mode

最后,我们会为文件输入添加一个事件监听器,并在标签下方显示文件的名称和大小。

const file = document.querySelector('#file');
file.addEventListener('change', (e) => {
  // Get the selected file
  const [file] = e.target.files;
  // Get the file name and size
  const { name: fileName, size } = file;
  // Convert size in bytes to kilo bytes
  const fileSize = (size / 1000).toFixed(2);
  // Set the text content
  const fileNameAndSize = `${fileName} - ${fileSize}KB`;
  document.querySelector('.file-name').textContent = fileNameAndSize;
});
Enter fullscreen mode Exit fullscreen mode

这就是全部情况。

文件输入部分就介绍到这里。你可以根据自己的喜好来设计样式,实现你想要的效果,这完全取决于你。祝你设计愉快!😁😁

文章来源:https://dev.to/ibn_aubakre/styling-file-inputs-like-a-boss-mhm