jQuery动画切换到精确的高度

时间:2014-01-09 12:57:43

标签: jquery if-statement jquery-animate height toggle

这完美地运作

$('.closeme').click(function() {
    $('.mybox').animate( { height:"30px" }, { queue:false, duration:500 });
});

BUT

如何切换回来?

(如果身高:“30px”转到原来的身高)?

这不是正确的jquery语法,只是为了得到这个想法:

$('.closeme').click(function() {
    if ! $('.mybox') = height:"30px" { 
        $('.mybox').animate( { height:"30px" }, { queue:false, duration:500 });
    }
    else {
        $('.mybox').animate( { height:"800px" }, { queue:false, duration:500 });
    }
});

5 个答案:

答案 0 :(得分:2)

只需将原始高度存储在某处,data()似乎是一个好地方

$('.mybox').data('height', $('.mybox').height());

$('.closeme').on('click', function() {
    var flag = $(this).data('flag'),
        ani  = 30;

    if (flag) ani = $('.mybox').data('height');

    $('.mybox').animate( { height: ani }, { queue:false, duration:500 });

    $(this).data('flag', !flag);
});

FIDDLE

答案 1 :(得分:2)

$('.closeme').click(function() {
    if ($('.mybox').height() != 30) {
        $('.mybox').animate( { height:"30px" }, { queue:false, duration:500 });
    } else {
        $('.mybox').animate( { height:"800px" }, { queue:false, duration:500 });
    }
});

DEMO

答案 2 :(得分:1)

请看一下这个例子。在html中添加类试试吧。

$(“。closeme”)。on(“click”,function(){

    var moveHeight;
    var className = "addProperty";

    if ($('.mybox').hasClass(className)) {

        $('.mybox').removeClass(className);
        moveHeight = "30px";

    }
    else {

        $('.mybox').addClass(className);
        moveHeight = "800px";

    }

    $('.mybox').animate({ height: moveHeight }, 500);

});

答案 3 :(得分:0)

工作小提琴:http://jsfiddle.net/patelmilanb1/6AVtH/

$('.closeme').click(function () {
    if ($(this).hasClass("showme")) {
        $('.mybox').animate({
            height: "500px"
        }, {
            queue: false,
            duration: 500
        });
        $(this).removeClass("showme").addClass("closeme").html("close me");
    } else {
        $('.mybox').animate({
            height: "30px"
        }, {
            queue: false,
            duration: 500
        });
        $(this).removeClass("closeme").addClass("showme").html("show me");
    }

});

答案 4 :(得分:0)

这应该是诀窍兄弟:     $('。closeme')。on('click',function(){     var flag = $(this).data('flag'),         ani = 30;

if (flag) ani = $('.mybox').data('height');

$('.mybox').animate( { height: ani }, { queue:false, duration:500 });

$(this).data('flag', !flag);
});