这一切都可以通过现代浏览器上的 CSS 来实现,另外还有以下好处:
- 不依赖 JavaScript
- 没有必要
tabindex
- 它通过空格或输入激活,这两者都是预期的行为。
关键是使输入在视觉上隐藏(使用.visually-hidden
类)但仍然可以聚焦,然后使用+
链接标签(不将输入包装在标签中)。
下面示例的关键部分是[type="file"]:focus + label
这使您可以在选择输入时更改标签样式(重要的是要在 DOM 中立即<label>
出现在DOM 之后才能使其正常工作)。<input>
我还包括了应用::before
样式hover
和focus
完整性的语法。
示例(不是生产就绪的解决方案)
下面给出的示例是演示如何实现目标的一种快速而肮脏的方式,它有几个可访问性问题需要在投入生产之前解决:-
- 你不应该使用相同的样式
hover
和focus
- >悬停你应该改变颜色并显示图标,焦点添加边框并显示图标
- 而不是使用字体作为图标,您应该使用 SVG,因为如果有人覆盖它们,字体可能会损坏(即,如果他们由于阅读障碍而有首选字体)。
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>