jQuery:将边距动画化为自动?
我正在尝试对图像进行动画处理,使其居中。这是我想使用的代码:
$('#myImage').animate({'margin-right': 'auto'});
但是当我这样做时,它会被忽略并且不会改变边距。
有没有办法将边距设置为自动动画,或以其他方式使图像居中?
谢谢!
I'm trying to animate an image so that it centers itself. Here's the code I'd like to use:
$('#myImage').animate({'margin-right': 'auto'});
But when I do that, it's ignored and doesn't change the margin.
Is there a way to animate a margin to auto, or otherwise center an image?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于“auto”不是数字,因此 jQuery 无法为其设置动画。
如果您同意将图像从文档流中取出,您可以将位置设置为绝对或固定,然后尝试:
As 'auto' isn't a number, jQuery cannot animate it.
If you are okay with taking the image out of the flow of the document, you can set position to absolute or fixed and try:
您无法为
auto
属性设置动画。要正确地将元素设置为屏幕中心的动画,您需要将其绝对定位(或其他),然后计算屏幕大小、元素大小和滚动位置。这是另一个所以回答类似的问题。 这是小提琴或者,如果您只想要水平对齐,您可以从动画功能中删除顶部。如果您确实想发挥创意,可以删除
position:absolute
,并在动画之后重新定位margin:auto
,以防屏幕大小调整。 查看另一个小提琴。You cannot animate an
auto
property. To properly animate the element to the center of the screen you will need to position itabsolutely
(or other) and then calculate the screen size, element size, and scroll position. Here is a another SO answer on something similar. Here is the FiddleAlternatively if you only want the horizontal alignment you can remove the top from the animate function. And if you really want to get creative you can remove the
position:absolute
, and repositionmargin:auto
after the animation in case of screen resizing. See another fiddle.扩展乔赛亚·鲁德尔的答案。如果你们需要图像在文档中保持流畅,请使用 Josiah 答案的修改版本。我的图像最初位于
margin: 0 -1000px
,并滑入计算出的左右边距。同时始终保持 dom 中的流动Expanding on Josiah Ruddell's answer. If you guys need your image to keep its flow in the document, use this modified version of Josiah's answer. My image was originally positioned at
margin: 0 -1000px
, and slides in to the calculated margin left and right. While keeping its flow in the dom the whole time