jQuery动画回到原来的位置

Von*_*ytt 5 jquery position jquery-animate

我有一个我正在研究的网站,它有一些绝对定位的div,我需要在点击时调整大小,然后这些将填充div所在的容器.问题是如何让它们切换到去回到原来的位置(顶部,左侧),每个位置都不同.

$(".work-item .toggle").toggle(function() {
        $(this).parent().animate({ height: '430', width: '930', top: '0', left: '0' }, 750);
    },
    function() {
        var pos         = $(this).parent();
        var position    = pos.position();      

        $(this).parent().animate({ height: '150', width: '200', top: position.top, left: position.left }, 750);
    });
Run Code Online (Sandbox Code Playgroud)

尝试以上但是它的新位置不是原来的.

提前致谢.

PVS

Nic*_*ver 12

您可以在首次加载页面时存储位置$.data()并在以后使用它,如下所示:

$(".work-item .toggle").each(function() {
  $.data(this, 'position', $(this).parent().position());
}).toggle(function() {
  $(this).parent().animate({ height: '430', width: '930', top: '0', left: '0' }, 750);
}, function() {
  var position = $.data(this, 'position');
  $(this).parent().animate({ height: '150', width: '200', top: position.top, left: position.left }, 750);
});
Run Code Online (Sandbox Code Playgroud)

这将在.position()绑定之前为每个元素的父元素存储,然后在稍后动画时使用它.