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

JavaScript实现SVG矩形点击切换尺寸功能遇故障求助

解决SVG矩形点击切换尺寸的问题

我来帮你排查这个点击切换SVG正方形尺寸的问题,你的代码有几个小问题需要修正,我一步步拆解给你:

问题分析

  1. 全局event对象的兼容性问题:
    现在多数现代浏览器(尤其是严格模式环境下)不会自动将event暴露为全局变量,直接使用会导致event未定义的错误,所以需要把事件对象作为参数传递给函数。

  2. 未完成的代码片段:
    你代码里的event.target.setAttrib是未完成的语法,这会直接导致函数执行中断,必须删除或者补全(如果不需要额外属性的话直接删掉即可)。

  3. 属性值的类型判断隐患:
    getAttribute("width")返回的是字符串类型,你直接和数字100比较,虽然JS会做隐式类型转换,但显式转成数字再比较会更可靠,避免意外的类型匹配问题。

  4. 缺失反向切换逻辑:
    目前你只写了从100px切换到50px的逻辑,没有处理从50px切回100px的分支,导致点击一次后就无法恢复原状。

修正后的完整代码

HTML(SVG示例)

<!-- 示例网格,每个矩形绑定点击事件时传递event参数 -->
<svg width="400" height="400">
  <rect x="0" y="0" width="100" height="100" fill="#ccc" onclick="clickChng(event)" />
  <rect x="100" y="0" width="100" height="100" fill="#ddd" onclick="clickChng(event)" />
  <rect x="0" y="100" width="100" height="100" fill="#ddd" onclick="clickChng(event)" />
  <rect x="100" y="100" width="100" height="100" fill="#ccc" onclick="clickChng(event)" />
</svg>

JavaScript函数

function clickChng(event) {
  // 拿到当前点击的矩形元素
  const targetRect = event.target;
  // 获取当前宽度并转为数字类型
  const currentWidth = parseInt(targetRect.getAttribute("width"));

  // 双向切换尺寸逻辑
  if (currentWidth === 100) {
    targetRect.setAttribute("width", 50);
    targetRect.setAttribute("height", 50);
    // 如果需要保持网格居中,可添加位置调整逻辑
    // targetRect.setAttribute("x", parseInt(targetRect.getAttribute("x")) + 25);
    // targetRect.setAttribute("y", parseInt(targetRect.getAttribute("y")) + 25);
  } else {
    targetRect.setAttribute("width", 100);
    targetRect.setAttribute("height", 100);
    // 对应恢复位置
    // targetRect.setAttribute("x", parseInt(targetRect.getAttribute("x")) - 25);
    // targetRect.setAttribute("y", parseInt(targetRect.getAttribute("y")) - 25);
  }
}

额外说明

  • 我用const替代了var,这是现代JavaScript的最佳实践,能避免变量提升带来的潜在问题。
  • 注释里的位置调整逻辑是可选的,如果你的网格需要正方形切换后保持居中显示,可以取消注释这段代码,不然切换后正方形会左上角对齐,可能导致网格布局错乱。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:28:39