10

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>

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.

i knew so many custom plugin is there like raphel.js.

http://raphaeljs.com/

but i don't want to use custom plugin to do this. i want to do this simply in jquery.animate function.

is this possible ?

Thanks,

Siva

4

5 に答える 5

1

私はこのようなことを試してみます

<svg>
    <rect class="myElement" id="rect1" x="10" y="20" width="100px" height="100px">
</svg>

スクリプトで:

var myElemX = $('.myElement').attr('x');
var myElemY = $('.myElement').attr('y');
$("#rect1").animate({
    left: myElemX+'px',
    top:  myElemY+'px'
}, 1500 );
于 2013-06-28T08:59:05.420 に答える
1

ここでのすべての回答は、SVG に固有のものか、.animate() jQuery 呼び出しを再実装したものです。アニメーションの開始時に属性が 0 にリセットされるという問題に遭遇することなく、jQuery 呼び出しを使用する方法を見つけました。

id を持つ img タグ要素のwidthand属性をアニメーション化したいとしましょう。現在の値から 300 にアニメートするには、次のようにします。heightimage

var animationDiv= $("<div></div>"); //we don't add this div to the DOM
var image= $("img#image");
//could use any property besides "top" and "left", but the value must be valid, that means concatenating a "px" to numerical attributes if they don't have it already (and removing them in the step callback if they do)
animationDiv.css("left", image.attr("width")); 
animationDiv.css("top", image.attr("height")); 
animationDiv.animate(
    {
        left: 300,
        top: 300
    },
    {
        duration: 2500,
        step: function(value, properties) {
            if (properties.prop == "left")
                 image.attr("width", value + "px")
            else
                 image.attr("height", value + "px")
        }
    }
)

このアプローチでは、DOM 内にない div を使用してその値をアニメーション化し、次に div CSS 値を使用して要素をアニメーション化します。あまりきれいではありませんが、アニメーションを停止する必要がある場合は、animationDiv を呼び出すことができます.stop()

jsfiddle

于 2014-12-31T10:28:37.870 に答える
-1

これはあなたに簡単に合うかもしれません

$("your div id").css("position", "absolute").animate({
    left: 159,
    top:  430
});
于 2013-12-22T12:31:47.267 に答える