jQuery:Animate Margins to Auto?

我正在尝试为图像设置动画,使其自身居中。 这是我想要使用的代码:

$('#myImage').animate({'margin-right': 'auto'}); 

但是,当我这样做时,它被忽略,并没有改变边际。
有没有办法将边距设置为自动或以图像为中心?

谢谢!

由于’auto’不是数字,jQuery无法为其设置动画。

如果您可以将图像从文档流中取出,可以将位置设置为绝对或固定并尝试:

 $('#myImage').animate({'left': '50%', 'margin-left': -$('#myImage').width()/2 }); 

您无法为auto属性设置动画。 要将元素正确地设置为屏幕中心的动画,您需要absolutely (或其他)定位它,然后计算屏幕大小,元素大小和滚动位置。 这是另一个类似的回答 。 这是小提琴

 jQuery.fn.center = function () { this.css("position","absolute"); var top = ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px", left = ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px"; this.animate({top: top, left: left}); return this; } 

或者,如果您只想要水平对齐,则可以从动画function中移除顶部。 如果你真的想要发挥创意,你可以删除position:absolute和重新定位margin:auto在屏幕大小调整后动画后margin:auto 。 看另一个小提琴 。

 jQuery.fn.center = function () { this.css("position","absolute"); var left = ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px"; this.animate({left: left}, function(){ $(this).css({position: 'static', margin: '0 auto'}); }); return this; } $('#selector').center(); 

扩展Josiah Ruddell的答案。 如果你们需要你的图像来保持其在文档中的流量,请使用Josiah的答案的这个修改版本。 我的图像最初位于边距:0 -1000像素,并向左和向右滑入计算边距。 同时保持其在dom中的流量

 jQuery.fn.center = function () { var margin = ( $(window).width() - this.width() ) / 2; this.animate({marginLeft: margin, marginRight: margin}, function(){ $(this).css({margin: '0 auto'}); }); return this; 

}

    Interesting Posts