当前位置: 动力学知识库 > 问答 > 编程问答 >

jquery - Toggle a Div container height

问题描述:

I am working on a button on which the toggle applies and the div height increases and decreases.

So what i am trying to do is that on a button lets say on #about click the #aboutsubmenu shows and the height of #maincontainer increases and on same click if if it's open it closes.

Here is what i am trying to do

$(document).ready(function() {

$('#aboutsubmenu').hide();

var opened;

var opened2;

$('#about').click(function() {

opened = "no";

if (opened == "no") {

$('#aboutsubmenu').show();

$('#maincontainer').css('height', '387px');

opened = "yes";

}

else if (opened == "yes") {

}

});

});

I am totally confused here. Can you help me out.

网友答案:

Try this, Initialize your variable outside event handler

var opened = "no"; //
var opened2;
$('#about').click(function () {
    if (opened == "no") {
        $('#aboutsubmenu').show();
        $('#maincontainer').css('height', '387px');
        opened = "yes";
    } else if (opened == "yes") {
        $('#aboutsubmenu').hide();
        $('#maincontainer').css('height', '100px');
        opened = "no";
    }
});
网友答案:

Try this code:

$(document).ready(function () {
    $('#aboutsubmenu').hide();
    var opened = false;
    $('#about').click(function () {
        $('#aboutsubmenu').toggle(); // Toggle visibility
        $('#maincontainer').height(opened ? 387 : 100);
        opened = !opened;
    });
});

What you did wrong:

opened = "no";

that code at the start of the function makes it alwasy open.

分享给朋友:
您可能感兴趣的文章:
随机阅读: