问题描述
ASAIK jquery动画函数仅接受样式属性.但我想为元素的属性设置动画.考虑一个SVG元素矩形
ASAIK jquery animate function accepts style properties only. but i want to animate the attributes of an element. consider a SVG element rectangle
<svg>
<rect id="rect1" x=10 y=20 width="100px" height="100px">
</svg>
我想为矩形元素属性"x"和"y"制作动画,如下所示:
i want to animate the rectangle element attribute "x" and "y" something like below
$("#rect1").animate({
x: 30,
y: 40
}, 1500 );
但这不是正确的方法,因为动画功能会影响样式而不是元素的属性.
but it is not correct way because animate function affects style not attribute of an element.
我知道那里有很多自定义插件,例如 raphel.js .
i knew so many custom plugin is there like raphel.js.
但是我不想使用自定义插件来做到这一点.我只想在jquery.animate函数中做到这一点.
but i don't want to use custom plugin to do this. i want to do this simply in jquery.animate function.
这可能吗?
谢谢
Siva
推荐答案
只是为老式方法制作动画:
just animate the old fashioned way:
您可以通过类似jquery的方式调用animate
.
you can call animate
in a jquery like fashion.
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, function(k,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
);
});
这篇关于jQuery动画元素属性不是样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!