jquery:我可以设置位置的动画:绝对位置:相对?

我有一堆绝对定位的图像,我想能够点击一个按钮,让它们全部动画到它们通常在页面上的位置,如果它们有位置:相对。

所以甚至可以从位置:绝对到位置动画:相对于jquery?

这就是我所拥有的:

$(".change_layout").click(function(){ $(".book_img").animate({position:'relative', top:'0px', left:'0px'}, 1000) }) 

不,你不能直接为它制作动画,但你可以找到终点并在那里制作动画。 当动画到static位置时,这样的东西可能会起作用:

 $('img.foo').each(function() { var el = $(this); // Make it static el.css({ visibility: 'hidden', // Hide it so the position change isn't visible position: 'static' }); // Get the static position var end = el.position(); // Turn it back to absolute el.css({ visibility: 'visible', // Show it position: 'absolute' }).animate({ // Animate to the static position top: end.top, left: end.left }, function() { // Make it static $(this).css('position', 'static'); }); }); 

它有点hacky,但它应该工作。

我认为你不能这样做。 jQuery animate仅适用于任何“数字CSS属性”。

没有。

但是,您可以检查元素的当前位置(调用.position() ),将position设置为relative ,并将原始位置的动画设置为当前位置。

我喜欢Tatu的解决方案,但发现这个可重用的代码更符合我的目的:

 function specialSlide(el, properties, options){ //http://stackoverflow.com/a/2202831/ el.css({ visibility: 'hidden', // Hide it so the position change isn't visible position: 'static' }); var origPos = el.position(); el.css({ visibility: 'visible', // Unhide it (now that position is 'absolute') position: 'absolute', top: origPos.top, left: origPos.left }).animate(properties, options); } 

假设我想将$(’#elementToMove’)滑动到一个新位置,我希望它需要1000毫秒才能移动。 我可以这样称呼:

 var props = {'top' : 200, 'left' : 300}; var options = {'duration': 1000}; specialSlide($('#elementToMove'), props, options);