使用outerHeight();测量相同的类名,但具有不同的高度

时间:2014-01-08 13:58:26

标签: javascript jquery html css

动画的距离取决于item0高度。但是,当我使用辅助类来改变div的高度时,jQuery不会将新的高度付诸实践。

是否可以考虑新的高度,由新的类名给出?

http://jsfiddle.net/tmyie/28N7M/1/

jQuery的:

    var height = $('.item0').outerHeight();

    $('p').click(function(){
        $('.item0').animate({top:height}, 300);

    });

HTML:

    <p>click here</p>

    <div class="item0"></div>
    <div class="item0"></div>
    <div class="item0"></div>
    <div class="item0 half"></div>

CSS

.item0 {
    background-color: red;
    height: 50px;
    width: 25px;
    float: left;
    margin-left: 5px;
    position: relative;
}

.half {
    height: 10px;
    background-color: blue;
}

2 个答案:

答案 0 :(得分:3)

$('p').click(function(){
     var $this;
     $('.item0').each(function() {
        $this = $(this);
        $this.animate({
            top: $this.outerHeight()
        }, 300);
     });
});

DEMO

答案 1 :(得分:0)

您首先计算高度,然后定义click事件处理程序。显然你只计算过一次高度,你应该重新计算它。您还需要为每个项目计算它。

只需点击一下计算身高:

$('p').click(function () {
    $('.item0').each(function() {
        var height = $(this).outerHeight();

        $(this).animate({top:height}, 300);
    });
});