首页 > 解决方案 > 使用 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>

标签: javascripthtmlcssinputaccessibility

解决方案


警告以下只是如何通过设置实际输入的样式并在视觉上隐藏标签(以确保它仍然可以访问)来实现此目的的快速想法。

但是,您仍然需要考虑许多可访问性问题,例如显示选择了哪个文件。

但这确实向您展示了如何设置输入样式以保留所有本机功能,而无需自己重新实现(例如活动状态,我在此处设置了样式)。也不要忘记自定义焦点指示器,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>


推荐阅读