我使用 focusable 属性来强制 SVG 元素在 HTML 文档中获得焦点。
我需要通过 TAB 键在 SVG 标签中的 SVG 元素中导航。就像文档中提到的 ( http://www.w3.org/TR/SVGTiny12/interact.html#focusable-attr )
但是我做不到。我已将 focusable
属性设置为 true
,并将每个元素的 tabindex
设置为 0
。
这是我的代码:
<div style="border: solid yellow 2px;" tabindex="0">
<svg tabindex="0" width="900px" height="500px" viewBox="0 0 95 50" style="border: solid red 1px;" focusable="true"
xmlns="http://www.w3.org/2000/svg">
<g data-Name="group" tabindex="0" stroke="green" fill="white" stroke-width="5" data-tabindex="0" style="border: solid green 1px;" focusable="true">
<circle tabindex="0" cx="20" cy="25" r="5" focusable="true" data-Name="shape 1" data-tabindex="0" />
<circle tabindex="0" cx="40" cy="25" r="5" focusable="true" data-Name="shape 2" data-tabindex="0" />
<circle tabindex="0" cx="60" cy="25" r="5" focusable="true" data-Name="shape 3" data-tabindex="0" />
<circle tabindex="0" cx="80" cy="25" r="5" focusable="true" data-Name="shape 4" data-tabindex="0" />
</g>
</svg>
我已经在谷歌浏览器中测试了代码。有什么方法可以达到目的吗?
最佳答案
正如@Robert Longson 在评论中提到的,SVG 1.2 从未最终确定,并且 SVG 1.2 Tiny 未由网络浏览器实现。 SVG 2 将有一个 tabIndex
属性,与 HTML 中的目的相同,但仍有一些细节需要解决,许多浏览器尚未实现(Chrome、IE 和 Firefox 确实尊重 HTML 页面中 SVG 元素的 tabIndex
)。
然而,与此同时,大多数浏览器将允许 <a>
如果 SVG 中的元素具有 xlink:href
,则链接这些元素以获得键盘焦点属性(即使它是像 #
这样的无操作链接)。您无法控制 Tab 键顺序,也无法通过脚本控制焦点,但您可以允许用户循环浏览元素,并且链接将接收用户输入事件。
以下代码段会在包含圆圈的链接获得用户焦点时更改圆圈的样式。
svg {
max-height: 100vh;
max-width: 100vw;
}
a:focus {
fill: blue;
fill-opacity: 0.5;
outline: none;
}
<svg width="900px" height="500px" viewBox="0 0 95 50" style="border: solid red 1px;"
xmlns="http://www.w3.org/2000/svg">
<g data-Name="group" stroke="green" fill="white" stroke-width="5" data-tabindex="0" >
<a xlink:href="#">
<circle cx="20" cy="25" r="5" data-Name="shape 1" data-tabindex="0" />
</a>
<a xlink:href="#">
<circle cx="40" cy="25" r="5" data-Name="shape 2" data-tabindex="0" />
</a>
<a xlink:href="#">
<circle cx="60" cy="25" r="5" data-Name="shape 3" data-tabindex="0" />
</a>
<a xlink:href="#">
<circle cx="80" cy="25" r="5" data-Name="shape 4" data-tabindex="0" />
</a>
</g>
</svg>
关于javascript - SVG 可聚焦属性不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22671799/