【发布时间】:2011-05-29 12:04:51
【问题描述】:
我正在尝试为图像设置动画,使其居中。这是我想使用的代码:
$('#myImage').animate({'margin-right': 'auto'});
但是当我这样做时,它会被忽略并且不会改变边距。
有没有办法让边缘自动设置动画,或者以其他方式居中图像?
谢谢!
【问题讨论】:
标签: javascript jquery css jquery-animate center
我正在尝试为图像设置动画,使其居中。这是我想使用的代码:
$('#myImage').animate({'margin-right': 'auto'});
但是当我这样做时,它会被忽略并且不会改变边距。
有没有办法让边缘自动设置动画,或者以其他方式居中图像?
谢谢!
【问题讨论】:
标签: javascript jquery css jquery-animate center
因为 'auto' 不是数字,所以 jQuery 无法对其进行动画处理。
如果您可以将图像从文档流中取出,您可以将位置设置为绝对或固定并尝试:
$('#myImage').animate({'left': '50%', 'margin-left': -$('#myImage').width()/2 });
【讨论】:
您不能为auto 属性设置动画。要将元素正确设置到屏幕中心,您需要将其定位为absolutely(或其他),然后计算屏幕大小、元素大小和滚动位置。这是类似的another SO answer。 Here is the Fiddle
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;
}
或者,如果您只想要水平对齐,您可以从动画函数中删除顶部。如果您真的想获得创意,您可以删除position:absolute,并在动画后重新定位margin:auto,以防屏幕调整大小。 See another fiddle.
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 答案版本。我的图像最初定位在margin: 0 -1000px,然后左右滑入计算出的边距。始终保持其在 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;
}
【讨论】: