2014-01-31 30 views
0

我試圖讓div來跟隨他的同胞div的最低邊界,而它改變高度。有幾個事件會導致高度發生變化,我正在考慮將這個功能添加到所有這些功能中。然而,它沒有按預期工作。下面是一些代碼:做一個div幻燈片,而另一個div的高度變化

HTML:

<div class="container"> 
    <div id="resForm"> 
     <div href class="bookCommentsToggle">Click Here</div> 
     <div class="bookComments"></div> 
    </div> 
    <div class="adjustPriceHeight"></div> 
    <div class="machine-right"></div> 
    <div style="clear:both;"></div> 
</div> 

CSS:

.container { 
    height:400px; 
    width:400px; 
    background:#ccc; 
} 
#resForm { 
    float:left; 
    width:200px; 
    background:yellow; 
} 
.bookCommentsToggle { 
    height:50px; 
    cursor:pointer; 
} 
.bookComments { 
    width:100px; 
    height:300px; 
    background:red; 
    display:none; 
} 
.machine-right { 
    float:right; 
    height:50px; 
    width:200px; 
    background:blue; 
} 
.adjustPriceHeight { 
    width:200px; 
    background:#fff; 
    float:right; 
} 

的jQuery:

function adjustPriceH() { 
    var totalHeight = $('#resForm').outerHeight(), 
     priceHeight = $('.machine-right').outerHeight(), 
     pushPrice = totalHeight - priceHeight; 

    $('.adjustPriceHeight').css('height', pushPrice).slideDown('slow'); 
} 

$('.bookCommentsToggle').click(function() { 
    $('.bookComments').slideToggle('slow', function(){ 
     adjustPriceH(); 
    }); 
}); 

JSFiddle

我想.machine-right到m因爲#resForm調整它的大小。我覺得我很接近,但還沒有那麼完美。

希望看到通過不嘗試在回調執行編碼^^

回答

2

的一行代碼的解決方案,我通常從SO專家那裏獲得的一個,幸福的; .slideToggle(持續時間,回調

使其等待滑動完成後才觸發動畫;你需要它來完成高度的設置。

如果高度都是一樣的

所以取而代之,給.bookComments & .adjustPriceHeight相同的高度和display:none,並在同一時間滑動他們。你只需要添加clear:right.machine-right和你的jQuery變爲:

$('.bookCommentsToggle').on('click', function() { 
    $('.bookComments, .adjustPriceHeight').slideToggle('slow'); 
}); 

做出了小提琴:http://jsfiddle.net/filever10/7xEUZ/

如果高度會有所不同

你需要刪除slideDown從你的函數中防止出現衝突命令的抖動。

function aph() { 
    var th = $('#resForm').outerHeight(), 
     ph = $('.machine-right').outerHeight(), 
     pp = th - ph; 
    $('.adjustPriceHeight').height(pp);//no need for css or slideDown here 
} 

//like @mainguy suggests, cause he's awesome 
$('.bookCommentsToggle').on('click', function() { 
    $('.bookComments').stop().slideToggle({ progress:aph }, 'slow'); 
}); 

做出了小提琴:http://jsfiddle.net/filever10/h5c4U/

+0

那甚至比我的回答更onelinerish。酷:-) – mainguy

+0

儘管無論哪種方式,他應該'清除:右'''.machine右''因爲這意圖。 – FiLeVeR10

+0

您的答案基於'.bookComments'和'.adjustPriceHeight'具有相同高度的前提,但有幾個事件會改變'#resForm'的高度。另一方面,這對於我的其他情況來說是一個乾淨的解決方案。 +1去單線程和+1(再次如果我可以)清理CSS。我不知道「清楚:是的」;「會讀到這一點。 –

2

不要在進步回調您的更新。

$('.bookCommentsToggle').click(function() { 
     $('.bookComments').slideToggle(
      { 
       progress:adjustPriceH 
      }, 'slow'); 
    }); 

fiddle

+0

我收到了一些應用此錯誤的錯誤,其中動畫的最後幾個步驟沒有被考慮到,所以存在一個間隙,因爲對象不像他們在你的小提琴上那樣對齊。我通過在'complete'回調中增加了第二次調用'adjustPriceH'的方法來解決它,但它看起來並不漂亮。你的答案雖然是正確的,但它可能是一個div,我看不到這會弄亂結果。 +1 –