【问题标题】:SVG parent animates but not the child SVGSVG 父动画但不是子 SVG
【发布时间】:2018-04-18 23:45:15
【问题描述】:

为什么父 SVG 旋转而子 SVG 不旋转?

注意第一个 SVG 的父元素会动画,但第二个 SVG 的子元素不会动画

在 Chrome 和 IE 11 中尝试过(是的,.parent-svg-1 在 IE 11 中旋转),两种浏览器的结果相同。 在 FireFox 中也试过:.child-svg-2 旋转但不是从其中心旋转。

$(document).ready(function() {

  setInterval(function() {

    let wd = 720 - 90
    let min = wd - 32.5
    let max = wd + 32.5
    let num = Math.floor(Math.random() * (max - min + 1) + min)

    // Note the parent element of the first SVG will animate,
    // but not the child element of the second SVG
    $('.parent-svg-1, .child-svg-2')
      .stop()
      .animate({
        rotate: num
      }, {
        step: function(now, fx) {
          $(this).css('transform', 'rotate(' + now + 'deg)')
        },
        duration: 500
      }, 'linear')
  }, 500)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<svg class="parent-svg-1" viewBox="0 0 60 60" width="50" height="50">
	<svg class="child-svg-1">
		<path d="M 10 30 L 20 20 L 20 25 L 50 25 L 50 35 L 20 35 L 20 40 Z" fill="#55f" />
	</svg>
</svg>

<svg class="parent-svg-2" viewBox="0 0 60 60" width="50" height="50" x="0" y="110">
	<svg class="child-svg-2">
		<path d="M 10 30 L 20 20 L 20 25 L 50 25 L 50 35 L 20 35 L 20 40 Z" fill="#f00" />
	</svg>
</svg>

【问题讨论】:

  • 他们都在 Firefox 上为我旋转。

标签: svg css-animations css-transforms


【解决方案1】:

在 SVG 1.1 中,&lt;svg&gt; 元素不支持 transform 属性。它适用于第一种情况,因为 SVG 嵌入在 HTML 中,并且转换由 HTML 布局引擎处理。不是 SVG 渲染代码。

在 SVG2 下,哪些浏览器仍在实施过程中,transform允许的。 Firefox 似乎已经实现了这一点,但 Chrome 还没有。

一个简单的解决方法是将子 &lt;svg&gt; 元素更改为 &lt;g&gt;

$(document).ready(function() {

  setInterval(function() {

    let wd = 720 - 90
    let min = wd - 32.5
    let max = wd + 32.5
    let num = Math.floor(Math.random() * (max - min + 1) + min)

    // Note the parent element of the first SVG will animate,
    // but not the child element of the second SVG
    $('.parent-svg-1, .child-svg-2')
      .stop()
      .animate({
        rotate: num
      }, {
        step: function(now, fx) {
          $(this).css('transform', 'rotate(' + now + 'deg)')
        },
        duration: 500
      }, 'linear')
  }, 500)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<svg class="parent-svg-1" viewBox="0 0 60 60" width="50" height="50">
	<svg class="child-svg-1">
		<path d="M 10 30 L 20 20 L 20 25 L 50 25 L 50 35 L 20 35 L 20 40 Z" fill="#55f" />
	</svg>
</svg>

<svg class="parent-svg-2" viewBox="0 0 60 60" width="50" height="50" x="0" y="110">
	<g class="child-svg-2">
		<path d="M 10 30 L 20 20 L 20 25 L 50 25 L 50 35 L 20 35 L 20 40 Z" fill="#f00" />
	</g>
</svg>

【讨论】:

    猜你喜欢
    • 2012-03-28
    • 2018-06-20
    • 2016-08-24
    • 2012-01-23
    • 2014-10-27
    • 1970-01-01
    • 2014-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多