2012-10-02 37 views
0

在我的index.html平滑转换SVG我:垂直使用jQuery

<ellipse id="ellipseRed" cx="500" cy="1300" rx="40" ry="150" />

在我的JavaScript文件我有:

$('ellipse').click(function() { 
    $(this).attr('transform', 'translate(0 -350) rotate(0)'); 
}); 

变换的作品,但它并不顺利。这似乎是“跳”到新的位置,而不是过渡到它。

我想单击SVG椭圆并使其缓慢地向上垂直移动。然后,如果我再次点击它,请慢慢向下移动。

我新的HTML,SVG和jQuery/JavaScript的

上午我甚至会对此正确的方法是什么?我应该使用jQuery来动画这个SVG吗?

回答

2

尽管可以使用jQuery为SVG制作动画效果,但它非常尴尬且效率不高。我建议使用具有良好SVG支持的库,如RaphaelD3

这是你会怎么做jQuery中:

//jQuery way, not recommended 
$('#ellipseRed').click(function() { 
    //min-height is just a placeholder value 
    //so jquery knows what values to put into 
    //the transformation 
    $(this) 
    .css({"min-height": 0}) 
    .animate(
     {"min-height": -350}, 
     {duration: 1000, 
     step: function(top){ 
      this.setAttribute("transform", "translate(0,"+top+")"); 
     } 
     }); 
}); 

比较清楚如何,这是在D3:

d3.select("#ellipseBlue").on("click", function(){ 
    d3.select(this) 
     .attr("transform", "translate(0,0)") 
     .transition() 
     .duration(1000) 
     .ease("in-out") 
     .attr("transform", "translate(0,-350)") 
}); 

您可以在这里找到一个演示:http://jsfiddle.net/LupTw/