2012-08-10 49 views
2

我一直在这几个小时,我只是无法弄清楚,对齐的div verticaly与jQuery

比方说,我有很多与漂浮的div,附带给他们,让jQuery的draggable ,他们的地位一直在变化。

现在我想能够将它们分隔开来,因此每个div之间的空间都是相同的,最大的问题之一就是每个div的高度也会不断变化。

每次我尝试做正确的时候,我只写了〜100行代码,我只是迷迷糊糊,也许有一些简单的方法来做到这一点,顺便说一句,这里是它的样子,我没有包含任何我写的代码,因为它没有多大意义。

http://jsfiddle.net/M6PmM/

+0

你想拖动事件时保持相同的垂直空间? – 2012-08-10 05:58:23

+0

@DiegoZoracKy不,应该只发生一次'按钮'被点击 – Linas 2012-08-10 06:18:32

回答

1

这是有趣的,看看你的问题的不同解释。当我想到垂直对齐时,我想到了Adobe Illustrator,以及如何均匀地分隔多个选定的形状。为此目的,你可以这样:

注意:这可以很容易地适应元素之间保持均匀的差距,无论他们的个人身高。

$('.align').click(function() { 

    // Cache the elements 
    var $obj = $('.obj'); 

    // Sort them by offset top 
    $obj = $obj.sort(function(a, b) { 
     return $(a).offset().top - $(b).offset().top; 
    }); 

    // Get get the offset of the first and last elements 
    // NOTE that we included the last element's height... you may need to tweak it 
    // here due to CSS borders adding to the height 
    var firstOffsetTop = $obj.first().offset().top; 
    var lastOffsetTop = $obj.last().offset().top + $obj.last().height(); 

    // The new container height is the difference between the first, 
    // and last element's position 
    var containerHeight = lastOffsetTop - firstOffsetTop; 

    // Determine the gap between each element, based on the height of the container 
    // divided by the number of elements 
    var spacing = containerHeight/$obj.length; 

    // Assign top properties 
    $obj.each(function(i, el) { 
     $(this).css('top', (i * spacing) + firstOffsetTop + 'px'); 
    }); 

}); 
+0

哇,这是真正接近我想要的,如果你可以请让它,所以最低和最高的div将留在它的位置,其他div在中间会根据这两个div对齐 – Linas 2012-08-10 06:21:28

+0

没问题,我已经更新了我的答案。有一个轻微的1-2像素移位,这很可能是由CSS边框增加高度/偏移量引起的,但我相信你会知道这一点;) – 2012-08-10 06:40:38

+0

是的,我会的,非常感谢你,我疯了有了这个 :/ – Linas 2012-08-10 06:50:31

0

晚,但这可能是另一种方式来做到:

$('.align').click(function(){ 

    var t = 0; 
    var dist = 10; 

    $('.obj').each(function(i,e){ 

     t += $('.obj').eq(i-1).height() + dist; 

     $(this).animate({ 

      left: $('.container').offset().left + dist, 
      top: t 

     }, 500); 

    }); 

});