You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FireFox 113中onkeydown属性失效问题求助

解决FireFox中SVG 元素键盘导航失效问题

问题分析

你的代码在Chrome和Edge中正常工作,但FireFox里<g>元素的onkeydown事件完全失效,核心原因是FireFox对SVG元素的聚焦与键盘事件处理存在特殊逻辑:

  • 即便设置了tabindex="0",FireFox中SVG元素默认可能不被标记为可聚焦对象,需要显式声明focusable="true"来开启聚焦能力。
  • 内联事件绑定(如onkeydown属性)在SVG元素上的兼容性表现不如标准事件监听方式。

修复方案

方案1:添加focusable属性(最小改动)

直接修改<g>标签,补充focusable="true"属性,保留原有内联事件逻辑:

<g id="county" tabindex="0" focusable="true" onkeydown="enterPress(event, 'Clarendon')" onclick="loadList('Clarendon')">
  <title>Clarendon</title>
  <path d="M 467.13 316.21 473.2 310.11 474.26 306.22 476.31 302.12 480.36 302.25 481.2 297.45 484.26 297.28 485.11 300.11 483.71 302.55 490.79 301.78 489.92 295.54 489.87 291.35 510.85 287.54 513.47 283.96 523.43 276.91 533.36 270.89 535.67 270.71 546.49 263.17 555.76 257.4 560.02 255.12 563.84 265.52 564.92 267.15 572.16 266.47 576.64 267.18 570.16 280.55 567.21 282.16 565.31 282.28 556.87 290.81 560.5 300.03 557.39 303.48 552.89 315.23 547.41 327.93 539.64 345.09 535.64 344.02 535.36 345.85 531.24 348.82 534.62 351.7 532.59 352.84 531.91 354.54 527.33 354.83 526.43 353.64 524.05 355.65 519.54 355.87 515.08 354.59 511.91 357.09 510.42 355.29 505.95 356.68 502.59 358.49 497.4 358.68 490.8 355.63 490.14 354.68 483.54 349.26 484.03 347.19 482.61 344.3 478.35 341.67 478.42 339.61 480.82 340.24 481.71 336.79 480.97 335.71 478.21 336.69 477.15 334.34 475.41 332.92 473.53 333.24 472.22 330.95 470.34 330.01 472.32 326.63 469.56 325.49 469.24 321.67 466.09 319.39 467.94 318.04 467.13 316.21 Z"
    id="Clarendon" fill="#b3c4db" />
  <text text-anchor="middle" x="100" y="500" font-family="Verdana" font-size="35" fill="blue" text-anchor="middle">Clarendon</text>
</g>

方案2:改用标准事件监听(更推荐,兼容性更稳定)

移除内联onkeydown属性,通过JS绑定事件,同时保留focusable="true":

<g id="county" tabindex="0" focusable="true" onclick="loadList('Clarendon')">
  <!-- 内部元素不变 -->
</g>
const loadList = (item) => console.log(item);
const countyElement = document.getElementById('county');

countyElement.addEventListener('keydown', (event) => {
  if (event.key === 'Enter') {
    loadList('Clarendon');
  }
});

额外优化:添加焦点可视化样式

为了直观确认元素是否成功获取焦点,可补充CSS:

#county:focus {
  outline: 2px solid #2196F3;
  outline-offset: 2px;
}

原理说明

  • focusable="true"明确告知FireFox该SVG元素允许被聚焦,解决了默认情况下不接收键盘事件的问题。
  • 使用addEventListener绑定事件,符合DOM事件标准,比内联属性的兼容性表现更一致。

内容的提问来源于stack exchange,提问作者milesdame

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 17:35:06