javascript jquery 将 div 动画到中心
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13739811/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jquery animate a div to the center
提问by Wouter Vandenputte
html:
html:
<div id="container">
<div id="header">
<div id="animate">
cartagena
</div>
</div>
what I want to do is to move the "animated" div to the center using Jquery.
我想要做的是使用 Jquery 将“动画”div 移动到中心。
my current js:
我目前的js:
$(document).ready(function() {
$("#animate").animate({left: "+=512"}, 2000);
});
and now I'd like to make it to the center instead of just 512 px to the right.
现在我想把它放在中心而不是右边 512 像素。
回答by Matthias
I am assuming that the position of #animate
is absolute
. To center the element in its parent element just add the half of its parent's width minus the half of its own width to left
:
我假设 的位置#animate
是absolute
。要将元素在其父元素中居中,只需将其父元素宽度的一半减去其自身宽度的一半添加到left
:
$("#animate").animate({
left: $("#animate").parent().width() / 2 - $("#animate").width() / 2
}, 2000);
I created a demousing jsFiddle.
我使用 jsFiddle创建了一个演示。
回答by Swarne27
You can use it this way to center it to the screen,
您可以使用这种方式将其居中显示在屏幕上,
Jquery
查询
$(document).ready(function() {
$("#animate").animate({left: $(window).width() / 2}, 2000);
});
css
css
<style type="text/css">
div
{
height: 50px; width: 50px; background-color: Red;position:absolute; top:0; left:0;
}
</style>
html
html
<div id="container">
<div id="header">
<div id="animate">
cartagena
</div>
</div>
</div>
回答by BernieSF
Asuming you want to center to window, use this code:
假设您要居中到窗口,请使用以下代码:
$("#myJQUIDialog").parent().position({
my: "center",
at: "center",
of: window,
using: function (pos, ext) {
$(this).animate({ top: pos.top }, 600);
}
});
This center the dialog, and animate at the same time, resulting in a smooth centering
这使对话框居中,并同时设置动画,从而实现平滑居中
回答by Vitor Hugo
Here it is other example, maybe it should be useful. I am using 'scroll' to make the effects.
这是另一个例子,也许它应该有用。我正在使用“滚动”来制作效果。
Hope it could help or be useful :)...
希望它可以帮助或有用:)...
<http://jsfiddle.net/p609dm7y/2/>
<http://jsfiddle.net/p609dm7y/2/>