CSS过渡动画未应用于内嵌svg <text>,但已应用于<rect>,它工作正常吗?

时间:2018-11-23 20:39:43

标签: javascript html css animation svg

如果单击该按钮,它将更改两个元素的位置,但是只有rect具有动画。

function myFunction() {
  document.getElementById("stackerCurrentSectBorder").setAttribute("y", "0%")
  document.getElementById("stackerCurrentSectCurrShift").setAttribute("y", "10%")
}
#stackerCurrentSect * {
  transition: .5s ease;
}
<svg id="statusBoardSVG" ref="statusBoardSVG" viewBox="0 0 500 300" xmlns="http://www.w3.org/2000/svg">
  <g id="stackerCurrentSect" ref="stackerCurrentSect">
    <rect x="30%" y="30%" width="31%" height="45%" rx="20" ry="20" fill="black" stroke="rgb(200,50,50)" stroke-width="1px" id="stackerCurrentSectBorder" ref="stackerCurrentSectBorder" />
    <text x="50%" y="50%" fill="rgb(120,120,120)" alignment-baseline="baseline" text-anchor="middle" font-size="80%" id="stackerCurrentSectCurrShift" ref="stackerCurrentSectCurrShift">current shift</text>
  </g>
</svg>

<button onclick="myFunction()">Click me</button>

<p id="demo"></p>

1 个答案:

答案 0 :(得分:0)

要使用CSS过渡,需要CSS属性进行动画处理。 <text> x和y属性不是。 (主要是因为它们可以获取可单独定位字形的值的列表。)

此外,<rect>元素的x和y只是在SVG 2规范中定义为CSS属性,尚未在所有浏览器中完全实现。

您可以轻松地使用transform属性。但是,您必须设置样式属性,而不是属性,因为该属性尚未使用单位标识符:

function myFunction() {
  document.getElementById("stackerCurrentSectBorder").style.transform = "translateY(-30%)"
  document.getElementById("stackerCurrentSectCurrShift").style.transform = "translateY(-40%)"
}
#stackerCurrentSect * {
  transition: .5s ease;
}
<svg id="statusBoardSVG" ref="statusBoardSVG" viewBox="0 0 500 300" xmlns="http://www.w3.org/2000/svg">
  <g id="stackerCurrentSect" ref="stackerCurrentSect">
    <rect x="30%" y="30%" width="31%" height="45%" rx="20" ry="20" fill="black" stroke="rgb(200,50,50)" stroke-width="1px" id="stackerCurrentSectBorder" ref="stackerCurrentSectBorder" />
    <text x="50%" y="50%" fill="rgb(120,120,120)" alignment-baseline="baseline" text-anchor="middle" font-size="80%" id="stackerCurrentSectCurrShift" ref="stackerCurrentSectCurrShift">current shift</text>
  </g>
</svg>

<button onclick="myFunction()">Click me</button>

<p id="demo"></p>

相关问题