6

我有以下 div :

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

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

我正在努力:

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

但它使用左上角作为参考来缩小 div。我怎样才能让它使用它的中心作为参考点?

谢谢你的帮助!

4

4 回答 4

5

top由于您的 div 使用and绝对定位margin-left,因此您还需要为它们设置动画:

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

对于编程方法,也可能更容易为 y 轴使用负边距。

于 2013-01-07T21:03:19.363 回答
4

这只是一个简单的 jQuery 插件

$.fn.resize = function( w, h ) {
  w = ( undefined !== w ? w : 50 );
  h = ( undefined !== h ? h : 50 );

  var cw = this.width();
  var ch = this.height();

  if ( 'static' === this.css( 'position' ) ) {
    this.css( {
      'position'    : 'relative',
      'top'         : '0px',
      'left'        : '0px'
    } );
  }

  this.stop().width( cw ).height( ch ).animate( {
    'top'    : '+=' + ( (ch - h) / 2 ) + 'px',
    'left'   : '+=' + ( (cw - w) / 2 ) + 'px',
    'width'  : w + 'px',
    'height' : h + 'px'
  } );
};

$( function() {
  $( '#shrink-test' ).resize(50,50);
} );

在这里测试它:http: //jsfiddle.net/bukfixart/nPjMa/1/

于 2013-01-07T21:28:59.670 回答
3

您可以像这样为顶部和左侧设置动画:

  $("#shrink-test").animate(
  {
      height: 50,
      width: 50,
      top: '+=25px',
      left: '+=25px'
  });

看到这个小提琴

于 2013-01-07T21:06:49.470 回答
2

您必须同时使用类似topand leftormargin属性为页面上的位置设置动画,如下所示:

$("#shrink-test").animate(
{
   height: 50,
   width: 50,
   top: '150px',
   left: '75%'
});

为每个使用适当的值。

于 2013-01-07T21:00:28.277 回答