0

通过创建标签并使用 css 隐藏输入元素,我创建了自己的自定义文件上传按钮。这一切都很好,但问题是我不能通过 tab 和 enter 使用按钮。我尝试将 tabindex=0 添加到标签中。然后我可以标签到元素 ok 但是单击 enter 时没有任何操作,因为它只是一个标签。

这是HTML代码

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

和 css 隐藏默认文件上传按钮

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

任何帮助深表感谢。

4

4 回答 4

1

这一切都可以通过现代浏览器上的 CSS 来实现,另外还有以下好处:

  • 不依赖 JavaScript
  • 没有必要tabindex
  • 它通过空格或输入激活,这两者都是预期的行为。

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

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

这使您可以在选择输入时更改标签样式(重要的是要在 DOM 中立即<label>出现在DOM 之后才能使其正常工作)。<input>

我还包括了应用::before样式hoverfocus完整性的语法。

示例(不是生产就绪的解决方案)

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

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

还要确保使用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%;
}
<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.2.0/css/all.css" />
<input type="file" id="inputName" class="visually-hidden"/>
<label for="inputName">upload</label>

于 2019-12-12T22:19:08.907 回答
0

我可能有一些可以提供帮助的小技巧。您可以focus-within在包含文件输入的父元素上使用属性并使用它设置样式

parent:focus-within {
  border: 1px solid blue;
  background: yellow;
}
于 2021-09-21T23:52:00.577 回答
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');
  }
})
于 2019-12-12T19:44:12.820 回答
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;
}
于 2019-12-12T18:57:59.007 回答