javascript - 使用 Enter 键打开选择文件对话框
问题描述
我的项目有问题
我想在“Enter”键上打开输入文件以提高一些可访问性。
我在标签上添加了 tabindex,因为当我使用 tab 跳转到这个标签并按“enter”时,我想触发将打开输入文件选择器的函数。
.input {
position: absolute;
visibility: hidden;
}
<input id="input" class="input" name="newFile" type="file" accept=".pdf" data-required="true" />
<label class="btn" for="input" tabindex="0">
<span class="upload label">
<span class="label__text" data-label="Upload file" data-next-label="Upload next file">Upload file</span>
</span>
</label>
解决方案
警告以下只是如何通过设置实际输入的样式并在视觉上隐藏标签(以确保它仍然可以访问)来实现此目的的快速想法。
但是,您仍然需要考虑许多可访问性问题,例如显示选择了哪个文件。
但这确实向您展示了如何设置输入样式以保留所有本机功能,而无需自己重新实现(例如活动状态,我在此处设置了样式)。也不要忘记自定义焦点指示器,input:focus::before
.
还有其他问题,例如浏览器支持也需要考虑,但是理论上这应该可以合理地回退,我只是还没有测试过。
这个 codepen为如何实现一些缺少的功能提供了一个很好的起点,例如显示选定的文件名。
input{
color: transparent;
width:150px;
height:28px
}
input::-webkit-file-upload-button {
visibility: hidden;
}
input::before {
content: 'Select a PDF';
color: black;
display: inline-block;
border: 1px solid #999;
border-radius: 3px;
padding: 5px 8px;
outline: none;
white-space: nowrap;
-webkit-user-select: none;
cursor: pointer;
text-shadow: 1px 1px #fff;
font-weight: 700;
font-size: 10pt;
width:132px;
}
input:hover::before {
border-color: black;
}
input:active {
outline: 0;
}
label {
position: absolute !important;
height: 1px;
width: 1px;
overflow: hidden;
clip: rect(1px 1px 1px 1px); /* IE6, IE7 */
clip: rect(1px, 1px, 1px, 1px);
white-space: nowrap; /* added line */
}
<input id="input" class="input" name="newFile" type="file" accept=".pdf" data-required="true"/>
<label for="input">upload file</label>
推荐阅读
- typescript - 如何制作递归元组来描述逻辑运算符?
- javascript - 如何在请求正文中发送带有日期对象的 axios 发布请求?
- regex - 正则表达式排除字符串并删除行
- php - 如何使用选择选项将 id 提取到数据库
- bash - Bash 脚本通过 term 和 MacOS launchd 进行不同的评估
- c# - 如何使用电子邮件 .net-core 发送生成的 pdf 附件
- android - 更新工具栏中的 androidx SearchView 文本颜色
- visual-studio-code - 为什么 docker 扩展在 Visual Studio 代码中不起作用
- c++ - 是否可以将类型转移到 C++ 方法或确定方法中的类型?
- command-line - 如何在命令行中将字符串添加到标准输入?