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 );
但这不是正确的方法,因为动画函数影响样式而不是元素的属性。
我知道有很多自定义插件,例如 raphel.js。
但我不想使用自定义插件来执行此操作。我想简单地在 jquery.animate 函数中执行此操作。
这可能吗?
谢谢
湿婆
最佳答案
只是用老式的方式制作动画:
你可以像时尚一样在jquery中调用animate
。
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 animate 用于元素属性而不是样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17360739/