在另一个div的高度发生变化时进行div滑动

时间:2014-01-31 12:59:36

标签: jquery css events height

我正试图让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移动#resForm调整它的大小。我觉得我很亲密,但还没到那里。

希望看到我通常从SO专家那里得到的单线解决方案之一,快乐编码^^

2 个答案:

答案 0 :(得分:2)

不试图在回调上执行; .slideToggle(持续时间,回调

让它等到幻灯片完成后再触发动画;你需要它来做高度计算的方式。

如果高度始终相同

相反,请.bookComments&amp; .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/

答案 1 :(得分:2)

在进度回调中进行更新。

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

fiddle

相关问题