【问题标题】:Second time clicking div closes and directly opens第二次点击div关闭直接打开
【发布时间】:2013-05-23 05:54:41
【问题描述】:

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

$( 文档 ).ready(function(e) { // 折叠和展开 $("#collapse").click( 功能() { $("#information").fadeOut(200); $("#leftColumn").animate({width:"10px"}, 200); $("#collapse").html("»"); $(this).click(function() { $("#information").fadeIn(200); $("#leftColumn").animate({width:"250px"}, 200); $("#collapse").html("«"); }); } ); });

【问题讨论】:

  • 请提供html结构
  • 您将一个新函数绑定到click() 事件。它不会覆盖第一个函数,因此在第二次单击时都会调用这两个函数。你可以看看toogle() 事件。

标签: javascript jquery toggle expand collapse


【解决方案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 ? "»" : "«");
    });
});

【讨论】:

  • 唯一不起作用的是 » 的 .html 更改
  • @Robbert - 糟糕,已修复!
【解决方案2】:

试试这个,

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;
    }
});

【讨论】:

    【解决方案3】:

    您覆盖了第一个 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("«");
                }
            }
        );
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-16
      • 2017-05-02
      • 1970-01-01
      • 2013-04-20
      • 1970-01-01
      • 2020-10-04
      • 1970-01-01
      相关资源
      最近更新 更多