SVG父级动画而不是子SVG

时间:2017-11-06 18:19:39

标签: svg css-animations css-transforms

为什么父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>

1 个答案:

答案 0 :(得分:1)

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

在SVG2下,哪些浏览器仍处于实施阶段,transform 是允许的。似乎Firefox实现了这一点,但Chrome还没有实现。

一个简单的解决方法是将子<svg>元素更改为<g>

&#13;
&#13;
$(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)
})
&#13;
<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>
&#13;
&#13;
&#13;