如何在jQuery中使用其中心作为参考点来缩小div? [英] How do I shrink a div using its center as reference point in jQuery?

查看:107
本文介绍了如何在jQuery中使用其中心作为参考点来缩小div?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下div:

<div id = "shrink-test" style = "position:absolute;top:100px;left:50%;margin-left:-50px;height:100px;width:100px;background-color: red;" />

,我想使用jQuery的animate()将div缩小到其大小的一半,但保持div的动画和位置居中.

and I want to use jQuery's animate() to shrink the div to half of its size but keep the animation and position of my div centered.

我正在尝试:

$("#shrink-test").animate(
{
   height: 50,
   width: 50
});

,但它会使用其左上角作为参考来缩小div.如何使用其中心作为参考点?

but it shrinks the div using its top left corner as reference. How can I make it use its center as the reference point?

感谢您的帮助!

推荐答案

由于使用topmargin-left绝对确定了div的位置,因此您还需要为其设置动画:

As your div is positioned absolutely by using top and margin-left, you will need to animate those as well:

$("#shrink-test").animate({
   height: 50,
   top: 125, // 100 + 50 / 2
   width: 50,
   marginLeft: -25 // 50 / -2
});

对于编程方法,在y轴上使用负边距也可能会更容易.

For a programmatical approach it might be easier to use a negative margin for the y-axis, too.

这篇关于如何在jQuery中使用其中心作为参考点来缩小div?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆