jQuery从元素的居中x坐标设置动画宽度

时间:2011-10-13 13:38:10

标签: javascript jquery css css3 jquery-animate

可以animate()制作平滑中心动画的元素的宽度吗?

我的意思是动画使元素固定在自己的x坐标上?

如果我这样做:

<a class="animate">hey</a>
$('.animate').animate({'width':'+=1%'},500);

它有效,但元素在右边动画而不是从他自己的中心

2 个答案:

答案 0 :(得分:3)

是的,你也必须移动元素。

<a class="animate" style="display:block; width:300px; border:1px solid #000; position:fixed; top:50px; left:50px;">hey</a>
jQuery(".animate").animate({'width':'0px', 'left':'200px'});

http://jsfiddle.net/7Ysbg/

新信息

所以你的意思是这样的:http://jsfiddle.net/7Ysbg/2/

jQuery(".animate").click( function(){
    var w = jQuery(".animate").width();
    var new_w = jQuery(".animate").width()*1.5;
    var left = jQuery(".animate").offset().left - ((new_w - w)/2);
    jQuery(".animate").animate({'width':new_w+'px', 'left':left+'px'}, 'fast');
});

答案 1 :(得分:1)

不仅可以设置宽度,还可以设置元素的位置。例如,您可以为left属性设置动画。在这种情况下,您的元素应position设置为relativeabsolute

var width = $('.animate').width();
$('.animate').animate({
    width: width*1.01,
    left: width*0.005
},500);