简体   繁体   中英

Toggle height of div size issue

I'm using the following code to toggle the size of a div:

var position = 'expanded';
var curHeight = $('.login-div').height();
$(".login-header").click(function() {
    if (position == 'expanded') {
        $('.login-div').animate({
            height: '3.2vw'
        });
        position = 'collapsed';
    } else {
        $('.login-div').animate({
            height: curHeight
        });
        position = 'expanded';
    }
});

My initial div height have no default size.Its height depends on content.So i'm trying to get the height of the div and use it at my second click,to change it's size back to normal.But somehow it doesn't take the correct height.My initial div has 260 px height,but the height() says it has only 238 px ...

I've created a little example. Not sure exactly what you meant with your question. Does this illustrate what you wanted to do?

 var positionExpanded,
     curHeight = $('.login-div').outerHeight();

$(".login-header").click(function() {
    if (positionExpanded) {
        $('.login-div').animate({
            height: '32vw'
        });
        positionExpanded = false;
    } else {
        $('.login-div').animate({
            height: curHeight
        });
        positionExpanded = true;
    }
});

Working demo here: http://jsbin.com/jivezilula/4/edit?html,css,js,output

如果您的元素在CSS中设置了边框或边距,并且希望将其包含在height值中,请使用outerHeight()

var curHeight = $('.login-div').outerHeight();
var position = 'expanded';
var curHeight = $('.login-div').height();
$(".login-header").click(function() {
    if (position == 'expanded') {
        $('.login-div').animate({
            height: '3.2vw'
        });
        position = 'collapsed';
    } else {
        $('.login-div').animate({
            height: curHeight
        });
        position = 'expanded';
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM