标签自定义文件上传按钮

时间:2019-12-12 18:48:57

标签: html css accessibility tabbing

我已经通过创建标签并使用CSS隐藏输入元素来创建了自己的自定义文件上传按钮。一切正常,但问题是我无法通过按Tab键输入该按钮。我尝试将tabindex = 0添加到标签。然后,我可以选择确定元素,但单击Enter时没有任何动作,因为它只是一个标签。

这是HTML代码

<label class="custom-file-upload>
<input type="file">
Choose file
</label>

和CSS隐藏默认的文件上传按钮

input[type="file"] {
    display: none;
}

非常感谢您的帮助。

3 个答案:

答案 0 :(得分:0)

您可以通过这种方式重写代码

<input id="file-upload" type="file">
<label for="file-upload" class="custom-file-upload>Choose file</label>

输入CSS并使用同级选择器相应地更改标签的CSS

input[type="file"] {
    opacity: 0;
}

答案 1 :(得分:0)

使用标签,您需要触发点击键盘事件才能输入

<label for ="file-upload1" tabindex="0" class="custom-file-upload">
<input type="file" id="file-upload"/> Choose file
</label> 

CSS

input[type="file"]{
  display:none;
} 

jQuery代码

$('.custom-file-upload').on('keyup',function(event){
  if (event.keyCode === 13) {
    $('#file-upload').trigger('click');
  }
})

答案 2 :(得分:0)

这一切都可以通过现代浏览器上的CSS实现,并具有以下附加优点:

  • 不依赖JavaScript
  • 不需要tabindex
  • 它会随着空间或回车而激活,这两者都是预期的行为。

关键是使输入在视觉上隐藏(使用.visually-hidden类,但仍可聚焦,然后使用+链接标签(不将输入包装在标签中)。

下面的示例的关键部分是[type="file"]:focus + label

这使您可以在选择输入时更改标签样式(重要的是,<label>在DOM中{strong>之后紧随出现在

为了完整性,我还包括了在<input>::before上应用hover样式的语法。

示例(非生产就绪解决方案)

下面给出的示例是演示如何实现目标的一种快速而肮脏的方法,它存在一些在将其投入生产之前需要解决的可访问性问题:-

  1. focushover不应使用相同的样式->悬停时应更改颜色并显示图标,聚焦添加边框并显示图标
  2. 您应该使用SVG而不是使用图标的字体,因为如果有人覆盖它们(例如,由于阅读困难而首选字体),字体可能会损坏。
  3. 如果人们通过使用focus媒体查询https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-reduced-motion
  4. 来表明他们喜欢减少移动,请确保禁用输入图标的动画。

还要确保使用标签上的prefers-reduced-motion: reduce和输入上的for="inputName"将标签与输入相关联。

id="inputName"
.visually-hidden { 
    position: absolute !important;
    height: 1px; 
    width: 1px;
    overflow: hidden;
    clip: rect(1px, 1px, 1px, 1px);
    white-space: nowrap;
}
[type="file"] + label {
  background: #f15d22;
  border: none;
  border-radius: 5px;
  color: #fff;
  cursor: pointer;
  display: inline-block;
  font-size: inherit;
  font-weight: 600;
  margin-bottom: 1rem;
  outline: none;
  padding: 1rem 50px;
  position: relative;
  transition: all 0.3s;
  vertical-align: middle;
  background-color: #99c793;
  border-radius: 50px;
  overflow: hidden;
}
[type="file"] + label::before {
  color: #fff;
  content: "\f382";
  font-family: "Font Awesome 5 Pro";
  font-size: 100%;
  height: 100%;
  right: 130%;
  line-height: 3.3;
  position: absolute;
  top: 0px;
  transition: all 0.3s;
}
[type="file"]:hover + label,
[type="file"]:focus + label{
  background-color: #497f42;
}
[type="file"]:hover + label::before, 
[type="file"]:focus + label::before {
  right: 75%;
}