我正在尝试对图像进行动画处理,以便它自己居中。这里是我想要使用的代码:jQuery:动画边距为自动?
$('#myImage').animate({'margin-right': 'auto'});
但是当我这样做时,它被忽略并且不会改变边距。
有没有一种方法可以将边距动画化为自动或以其他方式居中放置图像?
谢谢!
我正在尝试对图像进行动画处理,以便它自己居中。这里是我想要使用的代码:jQuery:动画边距为自动?
$('#myImage').animate({'margin-right': 'auto'});
但是当我这样做时,它被忽略并且不会改变边距。
有没有一种方法可以将边距动画化为自动或以其他方式居中放置图像?
谢谢!
由于'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;
}
或者如果只想水平对齐您可以从animate函数的顶部。如果你真的想要创意,你可以在动画后删除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();
扩展在约西亚Ruddell的答案。如果你们需要你的形象来保持它在文件中的流动性,请使用Josiah答案的这个修改后的版本。我的图像最初位于边距: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;
}
如果要动画垂直居中太,复制行,左顶部和宽度与高度更换。 – nsdel 2010-12-22 16:12:09