【问题标题】:How to get scale works cross-browser in center position on SVG elements with CSS如何使用 CSS 在 SVG 元素的中心位置跨浏览器进行缩放
【发布时间】:2018-08-06 23:57:18
【问题描述】:

我有一些 SVG 元素,应该在悬停时缩放(请参阅下面的附加代码 sn-p)。它在 WebKit 浏览器上运行良好(将 transform-origin: 50% 50%; 添加到 g 元素就可以了)。但是 Firefox 似乎以自己的方式扩展它(比如需要获得一些额外的 translate(x,y) 而 Edge 根本没有扩展它。你有什么建议?我做错了还是应该为不同的浏览器引擎使用单独的样式?我想用 CSS 解决它,但这只是一个例子。还有更多的 g 元素可以用不同的 x 和 y 位置进行缩放。

g {
    transition: all 0.5s;
    cursor: pointer;
    transform-origin: 50% 50%;
}

g:hover {
    transform: scale(1.5);
}
<svg height="260px" width="1106px" viewBox="0 0 1106 260">
  <g><rect fill="#ffffff" height="13" rx="2" ry="2" stroke="#b3b3b3" stroke-width="1" width="30" x="20" y="78.5"></rect><text fill="#999999" font-family="Verdana" font-size="9" x="25" y="88.5">REC</text></g>
  <g><rect fill="#ffffff" height="13" rx="2" ry="2" stroke="#b3b3b3" stroke-width="1" width="30" x="32.5" y="128.5"></rect><text fill="#999999" font-family="Verdana" font-size="9" x="37.5" y="138.5">REC</text></g>
</svg>

【问题讨论】:

  • 尝试将您的 SVG 包装在一个 div 中并缩放容器。在 Firefox 中对 SVG 应用一些转换也让我抓狂。
  • @fcalderan 这些矩形在一个 SVG 标记内,因此包装整个 SVG 以单独缩放其中的 g 元素,没有意义。还用div 包裹g 破坏了代码。

标签: css svg cross-browser scale css-transforms


【解决方案1】:

您假设转换框是填充框,但默认情况下它不是视图框。我已经调整了盒子模型以符合您在下面的期望。

g {
    transition: all 0.5s;
    cursor: pointer;
    transform-origin: 50% 50%;
    transform-box: fill-box;
}

g:hover {
    transform: scale(1.5);
}
<svg height="260px" width="1106px" viewBox="0 0 1106 260">
  <g><rect fill="#ffffff" height="13" rx="2" ry="2" stroke="#b3b3b3" stroke-width="1" width="30" x="20" y="78.5"></rect><text fill="#999999" font-family="Verdana" font-size="9" x="25" y="88.5">REC</text></g>
  <g><rect fill="#ffffff" height="13" rx="2" ry="2" stroke="#b3b3b3" stroke-width="1" width="30" x="32.5" y="128.5"></rect><text fill="#999999" font-family="Verdana" font-size="9" x="37.5" y="138.5">REC</text></g>
</svg>

g {
    transition: all 0.5s;
    cursor: pointer;
    transform-origin: 50% 50%;
}

g:hover {
    transform: scale(1.5);
}
<svg height="260px" width="1106px" viewBox="0 0 1106 260">
  <g><rect fill="#ffffff" height="13" rx="2" ry="2" stroke="#b3b3b3" stroke-width="1" width="30" x="20" y="78.5"></rect><text fill="#999999" font-family="Verdana" font-size="9" x="25" y="88.5">REC</text></g>
  <g><rect fill="#ffffff" height="13" rx="2" ry="2" stroke="#b3b3b3" stroke-width="1" width="30" x="32.5" y="128.5"></rect><text fill="#999999" font-family="Verdana" font-size="9" x="37.5" y="138.5">REC</text></g>
</svg>

【讨论】:

  • 感谢您的回答,它部分解决了我的问题(根据specification,这是相当新的东西,涵盖了 FF55+)但至少在 Edge 上,悬停行为没有奇怪,很高兴在新的 FF 浏览器上得到改进:)。您有什么建议可以防止在不支持transform-box 的 FF 版本上出现不良缩放?
  • 编辑 about:config 并设置 svg.transform-b​​ox.enabled,或者重写所有内容以便使用视图框
  • 感谢您的提示,但在浏览器中启用它仅用于测试,但从用户的角度来看,它是无用的。问题是如何正确地将其重写为视图框,请记住,视图框已生成,因此可能会改变以及缩放元素的位置。
猜你喜欢
  • 1970-01-01
  • 2021-03-19
  • 2013-05-27
  • 2019-02-04
  • 1970-01-01
  • 1970-01-01
  • 2017-11-10
  • 2012-11-03
  • 1970-01-01
相关资源
最近更新 更多