我有一個固定的外部div和三個div的情況,其中中間的一個是可切換的。在隱藏這個div時,我想讓底部div在同一時間增加高度,以便它佔據空的空間。jquery根據上面的元素動態地,平滑地調整底部元素
當中間div再次顯示時,我想同時降低底部div的高度。但是,即使我只是反轉隱藏代碼,底部div的高度不會按預期進行調整。
$(document).ready(function() {
\t var bottomHeight = $('#outer').height() - $('#top').height();
$('#bottom').css({'height': bottomHeight + 'px'});
});
// Hide toggle
$('.button a').click(function() {
\t var bottomHeight = $('#bottom').height(),
\t \t toggleHeight = $('#toggle').height(),
togglePadding = parseInt($('#top').css('padding-bottom')) * 2,
newHeight = bottomHeight + toggleHeight + togglePadding;
$('.hide').slideUp();
$('.show').slideDown();
\t $('#toggle').slideUp(400);
$('#bottom').animate({
height: newHeight + 'px'
}, {duration: 400, queue: false});
});
// Show toggle
$('.button a').click(function() {
\t var bottomHeight = $('#bottom').height(),
\t \t toggleHeight = $('#toggle').height(),
togglePadding = parseInt($('#top').css('padding-bottom')) * 2,
newHeight = bottomHeight - (toggleHeight + togglePadding);
$('.show').slideUp();
$('.hide').slideDown();
$('#toggle').slideDown(400);
$('#bottom').animate({
height: newHeight + 'px'
}, {duration: 400, queue: false});
});
#outer {
width: 200px;
height: 500px;
border: 1px solid black;
padding: 10px;
}
#toggle {
padding: 20px 0;
}
#bottom {
border: 1px solid red;
overflow-y: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="button show" style="display: none">
<a href="">Show</a>
</div>
<div class="button hide">
<a href="">Hide</a>
</div>
<div id='outer'>
<div id="top">
<div id="fixed">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Repellendus facere itaque similique, nulla quos quae, et suscipit est quia vitae aperiam magni ex error accusantium obcaecati repellat excepturi dolor facilis.
</div>
<div id="toggle">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima, eos laboriosam eveniet consequatur dolores, eaque molestias cupiditate quidem quasi mollitia. Vero sequi eos quia nostrum perspiciatis temporibus maxime ex? Numquam.
</div>
</div>
<div id="bottom">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Obcaecati quis dolorum ad molestias facere rerum expedita minus natus voluptatum debitis cumque dolore sint ea saepe neque necessitatibus est, optio dolorem.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nisi, fuga, soluta sint blanditiis optio similique, explicabo deleniti debitis veniam doloremque fugit qui voluptatem nulla magnam quos perspiciatis recusandae provident corrupti.</p>
</div>
</div>
將完整的jquery代碼包裝在document.ready中 –