javascript jQuery:动画宽度/高度,但保持居中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5182511/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 16:17:32  来源:igfitidea点击:

jQuery: Animating width/height, but Stay Centered

javascriptjqueryjquery-animate

提问by mellowsoon

I have an element on the page that I've already centered horizontally and vertically (It's a jQuery UI Modal Dialog), and want to resize it using .animate() like this:

我在页面上有一个元素,我已经水平和垂直居中(它是一个 jQuery UI 模态对话框),并想使用 .animate() 调整它的大小,如下所示:

<div id="element" style="width: 100px; height: 100px;">
    Hi Stack Overflow!
</div>

<script type="text/javascript">
    $('#element').animate({ height: "200px" });
</script>

That works fine, except the element only grows downwards. What I'm trying to do is have the element grow vertically in both directions (in this case 50px in each direction) so it stays centered. Is there a way that it can be done?

这工作正常,除了元素只向下增长。我想要做的是让元素在两个方向上垂直增长(在这种情况下,每个方向 50px)所以它保持居中。有没有办法做到?

回答by Loktar

Live Demo

现场演示

var growEl = $("#grow"),
    curHeight = $("#grow").height(),
    curTop = growEl.offset().top,
    newHeight = 200,
    newMargin = curTop -(newHeight -curHeight)/2;

if(newMargin < 0){
 newMargin = 0;   
}

$("#grow").animate({height:newHeight+"px", marginTop:newMargin + 'px'});

Formula for figuring out what to make the margin

计算利润的公式

NewTopMargin = CurrentMargin-(NewHeight-OldHeight)/2

Thanks @bobsoap for reminding me to use offset.top

感谢@bossoap 提醒我使用 offset.top

回答by benhowdle89

margin-top: -50px, height: 50px;

That sort of thing (sorry its not code formatted) i'm sure you can insert it correctly.

那种事情(对不起,它不是代码格式)我相信你可以正确插入它。