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

纯JS/CSS实现点击SVG椭圆切换选中样式 其余元素恢复未选中状态

SVG椭圆选中交互实现方案

核心实现思路

要适配大量椭圆元素的场景,最优方案是用事件委托,只给SVG父容器绑定1次点击事件,不用遍历每个椭圆组单独绑定事件,性能好、后续新增元素也不用改逻辑。
交互逻辑很简单:

  • 点击任意椭圆/椭圆上的文字时,先把所有椭圆组重置为未选中样式
  • 再把当前点击的椭圆组切换为选中样式

完整实现代码

你只需要在原有HTML的</body>标签前加一段JS代码即可,不需要改动原有DOM结构和CSS文件:

<!DOCTYPE html>
<html>
<head>
   <title>Experiment</title>
   <link rel="stylesheet" href="style.css">
</head>
<body>
   <h1>Major keys</h1>
    <svg viewBox="0 0 500 500" xmlns="http://www.w3.org/2000/svg">
    <g id="g-14" class="unselected-key">
       <ellipse cx="346.176" cy="15.569" rx="22.2" ry="22.2" />
       <text x="346.176" y="15.569">1</text>
    </g>
    <g id="g-15" class="unselected-key">
       <ellipse cx="451.176" cy="43.704" rx="22.2" ry="22.2" />
       <text x="451.176" y="43.704">2</text>
    </g>
    <g id="g-16" class="unselected-key">
       <ellipse cx="528.041" cy="120.569" rx="22.2" ry="22.2" />
       <text x="528.041" y="120.569">3</text>
    </g>
    </svg>

    <script>
      // 仅绑定1次事件到SVG容器,适配任意数量的椭圆组
      const svg = document.querySelector('svg');
      svg.addEventListener('click', (e) => {
        // 兼容点击椭圆、点击文字的场景,向上查找对应的key组元素
        const activeKey = e.target.closest('g.unselected-key, g.selected-key');
        if (!activeKey) return;

        // 全局重置所有选中态
        document.querySelectorAll('g.selected-key').forEach(item => {
          item.classList.replace('selected-key', 'unselected-key');
        });

        // 切换当前点击项为选中态
        activeKey.classList.replace('unselected-key', 'selected-key');
      })
    </script>
</body>
</html>

方案优势

  • 性能开销极低:哪怕SVG里有上百个椭圆元素,也只需要1个事件监听器,不用给每个元素单独绑定事件
  • 扩展性强:后续新增椭圆组时,只要给对应<g>标签加上初始的unselected-key类,不需要修改任何JS代码就能自动支持选中交互
  • 兼容性好:点击椭圆图形、点击椭圆上的文字都能正常触发选中,不会出现点击无响应的问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 07:16:02