第二次单击div关闭并直接打开

时间:2013-05-28 09:53:34

标签: javascript jquery toggle expand collapse

我正在制作一个可以展开和折叠的菜单。当我点击它我的代码工作正常并折叠div。如果我再次点击我的open en close div,它也会打开。但第二次这样做会导致我的div关闭并直接打开。有人能说出我做错了什么..


$( document ).ready(function(e) {

    // Collapse and expand
    $("#collapse").click(
        function() {
            $("#information").fadeOut(200);
            $("#leftColumn").animate({width:"10px"}, 200);
            $("#collapse").html("»");

            $(this).click(function() {
                $("#information").fadeIn(200);
                $("#leftColumn").animate({width:"250px"}, 200);
                $("#collapse").html("«");

            });
        }
    );


});

3 个答案:

答案 0 :(得分:1)

$(document).ready(function() {
    $("#collapse").on('click', function() {
        var w = parseInt( $("#leftColumn").css('width'),10 ) > 11;
        $("#information").fadeToggle(200);
        $("#leftColumn").stop(true,true).animate({width: w ? 10 : 250}, 200);
        $("#collapse").html(w ? "»" : "«");
    });
});

答案 1 :(得分:0)

你覆盖了第一个onclick函数 - 这就是你必须处理扩展/折叠有点不同的原因。此变体只是添加和删除一个类来决定应该使用哪个动画:

( document ).ready(function(e) {
    // Collapse and expand
    $("#collapse").click(
        function() {
            // default case
            if(!$(this).hasClass('collapsed')) {
                $(this).addClass('collapsed');
                $("#information").fadeOut(200);
                $("#leftColumn").animate({width:"10px"}, 200);
                $("#collapse").html("»");
            } else {
                // and in case it is collapsed...
                $(this).removeClass('collapsed');
                $("#information").fadeIn(200);
                $("#leftColumn").animate({width:"250px"}, 200);
                $("#collapse").html("«");
            }
        }
    );
});

答案 2 :(得分:0)

试试这个,

var toggle=0;
$("#collapse").click(function() {
    if(toggle==1){
        $("#information").fadeIn(200);
        $("#leftColumn").animate({width:"250px"}, 200);
        $("#collapse").html("«");
        toggle=0;
    }
    else
    {
        $("#information").fadeOut(200);
        $("#leftColumn").animate({width:"10px"}, 200);
        $("#collapse").html("»");
        toggle=1;
    }
});