jquery animate 用于元素属性而不是样式

标签 jquery svg jquery-animate jquery-svg

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

http://raphaeljs.com/

但我不想使用自定义插件来执行此操作。我想简单地在 jquery.animate 函数中执行此操作。

这可能吗?

谢谢

湿婆

最佳答案

只是用老式的方式制作动画:

你可以像时尚一样在jquery中调用animate

http://jsfiddle.net/wVv9P/7/

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/

相关文章:

reactjs - 为什么我在 react-native 中的 svg 没有显示任何阴影?

jquery - 在 chrome 中单击时旋转轮子的 js 文件

javascript - fakeLoader.js如何让页面流畅跳转?

php - Javascript 或 Jquery 中两个日期之间的天数

javascript - 如何使只读的tinyMCE编辑器再次可写

jQuery 将 css 类更改为 div

android - AnimatedVectorDrawable 可绘制路径的空路径

css - 动画虚线 SVG 线

javascript 在 I.E. 中不工作9 以及 Firefox

javascript - Jquery移动对象