ASAIK
jquery animate函数只接受样式属性.但我想为元素的属性设置动画.考虑一个SVG元素矩形
<svg> <rect id="rect1" x=10 y=20 width="100px" height="100px"> </svg>
我想为矩形元素属性“x”和“y”设置动画,如下所示
$("#rect1").animate({ x: 30,y: 40 },1500 );
但是它是不正确的方法,因为animate函数影响元素的属性不属于style.
但我不想使用自定义插件来做到这一点.我想简单地在jquery.animate函数中这样做.
这可能吗 ?
谢谢,
湿婆
解决方法
只是动画的老式的方式:
你可以像时尚一样在jquery中调用动画.
function animate($el,attrs,speed) { // duration in ms speed = speed || 400; var start = {},// object to store initial state of attributes timeout = 20,// interval between rendering loop in ms steps = Math.floor(speed/timeout),// number of cycles required cycles = steps; // counter for cycles left // populate the object with the initial state $.each(attrs,function(k,v) { start[k] = $el.attr(k); }); (function loop() { $.each(attrs,v) { // cycle each attribute var pst = (v - start[k])/steps; // how much to add at each step $el.attr(k,function(i,old) { return +old + pst; // add value do the old one }); }); if (--cycles) // call the loop if counter is not exhausted setTimeout(loop,timeout); else // otherwise set final state to avoid floating point values $el.attr(attrs); })(); // start the loop } $('button').on('click',function() { animate( $('#rect1'),// target jQuery element { x:100,y:300,width:50,height:100 },// target attributes 2000 // optional duration in ms,defaults to 400 ); });