键盘可聚焦的滚动条

从 Chrome 130 开始,如果滚动条没有可通过键盘聚焦的子项,则默认可通过键盘聚焦。

背景

滚动条无处不在。您可能会在“条款及条件”框中找到此信息,您需要滚动到底部才能点击提交按钮。或者,您可能会看到一个垂直菜单栏,其中包含许多可供选择的图标。

在这种情况下,许多网络用户会使用鼠标或触控板上的上下移动操作来滚动元素。不过,指针设备、触控板或触摸屏并不是每个用户浏览网页的最佳方式。有些用户更喜欢只使用键盘在 HTML 网页中导航,访问每个可聚焦元素。导致这种情况的原因有很多。包括手抖或其他导致难以操作鼠标的问题、难以视觉定位鼠标光标的问题,以及使用单个开关或语音控制功能的用户。

无障碍功能最佳实践建议所有功能都必须可通过键盘使用。这样,每个人都可以以最适合自己的方式使用网络。

2.1.1 键盘:内容的所有功能均可通过键盘界面操作,而无需为各个按键操作指定特定时间,但以下情况除外:底层功能需要的输入取决于用户移动的路径,而不仅仅是端点。(第 A 级)

在滚动条中实现焦点的更改之前

在此变更之前,只有在 tabindex 明确设置为 0 或更高时,滚动条元素才能获得 Tab 键焦点。例如,使用以下 CSS 和 HTML。然后,尝试使用 Tab 键从第一个按钮切换到滚动条元素。

div.scroll, button {
  border: 1px solid lightgray;
  margin-top: 1em;
  border-radius: 0.5em;
}

div.scroll {
  overflow: auto;
  width: 20em;
  height: 5em;
  display: block;
}
div.long {
  width: 10em;
  height: 10em;
}
<button>Start</button>
<div class="scroll" ta>b<i>ndex="0"
pThis is a tab f<oc>u<sable scroller..><./p
>d<i>v class="long"/div
pYou need to< s>c<roll> <down t>o s<ee this> line./p
/div
buttonEnd/button
由于 tabindex 为正值,滚动条可聚焦。

如果使用负 tabindex(如以下 HTML 中所示),系统会跳过滚动条。

<button>Start</button>
<div class="scroll" tab>i<n>dex="-1"
pThis is not a tab f<oc>u<sable scroller..><./p
>d<i>v class="long"/div
pYou cannot see< t>h<is l>i<ne usi>ng <the key>board./p
/div
buttonEnd/button
由于 tabindex 为负数,系统跳过了滚动条。

如果您未设置 tabindex 值,用户可能很难使用顺序焦点导航来访问滚动条。对于无法使用鼠标的用户来说,这可能会非常令人沮丧。

<button>Start</button>
<div class="sc>r<o>ll"
pThis scroller does not have a tabindex va<lu>e< set.../p
div cl><ass=>&<q>uot;long"/div
pYou cannot see this line< u>s<ing >t<he key>boa<rd./p
/>div
buttonEnd/button
滚动条没有 tabindex。

请注意,包含可聚焦子项的滚动条(如以下 HTML 所示)已经可供访问,因为当可聚焦子项获得焦点时,用户可以使用箭头键滚动。在这种情况下,行为不会发生任何变化。

<button>Start</button>
<div class="sc>r<o>ll"
pThis is a terms and conditions text. Please scroll down to acknowledg<e >r<eading./p
div cl><ass=>&<quot;long&quo>t;/div
butt<on id=&>q<uot;>B<">Ack<nowledg>e/button
/div
buttonEnd/button
由于包含可聚焦的子项,滚动条可聚焦。

从 Chrome 130 开始,支持可聚焦滚动条

此功能允许未设置 tabindex 值且没有任何可聚焦子项的滚动条可通过键盘聚焦。这样,无法或不想使用鼠标的用户就可以使用键盘上的 Tab 键和箭头键来聚焦内容。

<button>Start</button>
<div class="sc>r<o>ll"
pThis scroller does not have a tabindex va<lu>e< set.../p
div cl><ass=>&<q>uot;long"/div
pbut you can scroll <th>r<ough> <its co>nte<nt!/p
/>div
buttonEnd/button
滚动条没有 tabindex 或可聚焦子项,但仍然可聚焦。

请注意,只有当滚动条没有可聚焦的子项时,才会发生这种行为。 例如,如果滚动条已包含一个按钮,则 Tab 键焦点会跳过滚动条,直接聚焦到按钮。在这种情况下,当按钮获得焦点后,用户就可以使用箭头键访问滚动条内容。由于此规则,如果存在此类子项,默认项的行为可能并不总是最优。如果您希望滚动条元素本身在这种情况下可获得键盘焦点,建议将 tabindex 值设置为 0 或更高。

<button>Start</button>
<div class="scroll" ta>b<i>ndex="0"
pThis is a terms and conditions text. Please scroll down to <ac>k<nowledge reading><./p
>d<iv class=&quo>t;long"<;/div
b>u<tton> <id=&qu>ot;<B">Acknowledge/button
/div
buttonEnd/button
滚动条的 tabindex 为 0。

此功能可让滚动条在所有情况下都默认支持键盘操作,这有助于网页用户在标签页中浏览网页时获得更顺畅的体验。