jquery animate for element attributes not style

前端 未结 5 529
心在旅途
心在旅途 2021-01-11 18:40

ASAIK jquery animate function accepts style properties only. but i want to animate the attributes of an element. consider a SVG element rectangle

         


        
5条回答
  •  渐次进展
    2021-01-11 19:03

    just animate the old fashioned way:

    you can call animate in a jquery like fashion.

    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
        );
    });
    

提交回复
热议问题