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

有没有更简便的方法实现SVG rect元素的hover transform: scale()效果?

最优解决方案(纯CSS,无需JS)

不需要手动计算中心点,也不需要写JS,只要修正CSS的transform-box配置即可实现所有rect元素以自身中心点为原点缩放:

.cls-2{
  transition: transform 0.3s ease;
  /* 以元素自身的填充区域作为变换参考盒 */
  transform-box: fill-box;
  /* 直接设置原点为自身中心,浏览器会自动计算 */
  transform-origin: center;
}
.cls-2:hover{
  transform: scale(1.2);
}

之前的方案不生效是因为误将transform-box: fill-box写在了svg节点上,并且属性名写错成了transform: fill-box,只要把这两个属性配置到.cls-2上即可,所有rect元素的悬停效果会自动适配各自的中心点。


可选JS实现方案

如果有特殊场景需要用JS动态计算,可以用SVG原生的getBBox()API批量处理所有元素,无需手动逐个计算:

document.addEventListener('DOMContentLoaded', () => {
  document.querySelectorAll('.cls-2').forEach(rect => {
    // 获取元素在SVG坐标系内的实际坐标和尺寸
    const bbox = rect.getBBox();
    const centerX = bbox.x + bbox.width / 2;
    const centerY = bbox.y + bbox.height / 2;
    // 动态设置变换原点
    rect.style.transformOrigin = `${centerX}px ${centerY}px`;
  })
})

getBBox()返回的是元素的最小包围盒参数,不受元素嵌套、属性继承的影响,计算结果比直接读取x/y属性更准确。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 16:36:01