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); 

    }); 

});