简体   繁体   English

单击按钮时增加div的高度,再次单击同一按钮时将其减小

[英]increase height of div on button click, and decrease it when I click same button again

I have a div with height:0px and I want it to increase height to 300px when I click on a button. 我有一个height:0px的div,当我单击一个按钮时,我希望它将高度增加到300px。

When I click on the button again, I want it to get height of 0px again. 当我再次单击该按钮时,我希望它再次达到0px的高度。

CSS 的CSS

nav{
    height:0px;
    overflow:hidden;
    opacity:0;
}

JS JS

    $("#hamburger").click(function(){
            $('nav').stop().animate({ height: 300, opacity: 1 }, 'slow');
        },function(){
            $('nav').stop().animate({ height: 0, opacity: 0 }, 'slow');
    });

If I only use: 如果我仅使用:

$("#hamburger").click(function(){
        $('nav').stop().animate({ height: 300, opacity: 1 }, 'slow');
});

the animation works. 动画有效。 as soon as I add the other line, it doesn't. 一旦我添加另一行,它就没有。 I also tried using the toggle() function, but the result was that as soon as I load my page, the second part of the toggle function (which is height:0, opacity:0 ) loaded by itself. 我也尝试使用toggle()函数,但是结果是,一旦加载页面,切换函数的第二部分(即height:0, opacity:0 )就会自动加载。

here is a link to my website 这是我网站链接

Any ideas? 有任何想法吗? Thanks 谢谢

EDIT 编辑

I forgot to say that i am making my website responsive, and that this js code only concerns the mobile version, so to see the result, you should set your browser width to 480px or less 我忘了说我正在使我的网站具有响应能力,并且此js代码仅涉及移动版本,因此要查看结果,您应该将浏览器宽度设置为480px或更小

You're trying to call both functions at the same time. 您试图同时调用两个函数。 One function wants to increase the height of the div , and the other wants to decrease the height of the div . 一个函数要增加div的高度,另一个函数要减小div的高度。

Try something like this: 尝试这样的事情:

$("#hamburger").click(function(){
    var maxHeight = 300;

    if(+$('nav').height() < maxHeight) {

        $('nav').stop().animate({ height: 300, opacity: 1 }, 'slow');

    } else if (+$('nav').height() === maxHeight) {

        $('nav').stop().animate({ height: 0, opacity: 0 }, 'slow');

    }
});

To make it even shorter, you could do: 要使其更短,可以执行以下操作:

$("#hamburger").click(function(){
    var maxHeight = 300,
        nav = $('nav');

        nav.stop().animate({ height: +nav.height() < maxHeight ? 300 : 0, opacity: +nav.css('opacity') === 1 ? 0 : 1 }, 'slow');
});

By the way, the random + signs typecast any strings into numbers, just in case. 顺便说一句,以防万一,random +号将任何字符串都转换成数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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