我正在尝试使用JavaScript和CSS过渡动画各种SVG形状的属性。
例如:
HTML:
<svg width="400" height="400">
<circle id="circle" cx="200" cy="200" r="15" stroke="none" fill="blue" />
<rect id="rect" x="100" y="100" height="30" width="30" stroke="none" fill="red" />
</svg>
<button id="button">Animate</button>
JavaScript的:
document.getElementById("button").addEventListener("click", function () {
var circle = document.getElementById("circle");
var cx = 50 + Math.round(Math.random() * 300);
var cy = 50 + Math.round(Math.random() * 300);
// using 'setAttribute'
circle.setAttribute("cx", cx);
circle.setAttribute("cy", cy);
var rect = document.getElementById("rect");
var x = 50 + Math.round(Math.random() * 300);
var y = 50 + Math.round(Math.random() * 300);
// using 'setAttributeNS'
rect.setAttributeNS(null, "x", x);
rect.setAttributeNS(null, "y", y);
}, false);
CSS:
circle, rect {
-webkit-transition: all 0.7s ease-in-out;
-moz-transition: all 0.7s ease-in-out;
transition: all 0.7s ease-in-out;
}
这是一个完整的JSFiddle:http://jsfiddle.net/kkhvzyjq/
在Chrome中,这非常有效。但是,在Safari和Firefox中,当应用新属性(形状移动)时,没有过渡/动画。
有没有办法在这些浏览器中运行?
答案 0 :(得分:2)
Safari和Firefox不会转换位置属性的更改。
CSS属性transform
更适用于此:
http://jsfiddle.net/kkhvzyjq/7/
document.getElementById("button").addEventListener("click", function() {
var circle = document.getElementById("circle");
var cx = 50 + Math.round(Math.random() * 300);
var cy = 50 + Math.round(Math.random() * 300);
circle.style.transform = "translate(" + cx + "px," + cy + "px)";
var rect = document.getElementById("rect");
var x = 50 + Math.round(Math.random() * 300);
var y = 50 + Math.round(Math.random() * 300);
rect.style.transform = "translate(" + x + "px," + y + "px)";
}, false);
&#13;
circle,
rect {
-webkit-transition: all 0.7s ease-in-out;
-moz-transition: all 0.7s ease-in-out;
transition: all 0.7s ease-in-out;
}
&#13;
<svg width="400" height="400">
<circle id="circle" r="10" stroke="none" fill="blue" style="transform:translate(200px,200px);" />
<rect id="rect" height="10" width="10" stroke="none" fill="red" style="transform:translate(100px,100px);" />
</svg>
<button id="button">Animate</button>
&#13;