【问题标题】:How to add fade effect to .hide() and .show() without both showing如何在不显示的情况下向 .hide() 和 .show() 添加淡入淡出效果
【发布时间】:2023-07-27 08:56:01
【问题描述】:

我编写了示例代码来制作 2 个新标签和趋势

$(function() {
$("#t1").click(function() {
    $("#t2").removeClass("current");
    $(this).addClass("current");
    $("#newTrend").hide();
    $("#newContent").show();
});
$("#t2").click(function() {
    $("#t1").removeClass("current");
    $(this).addClass("current");
    $("#newContent").hide();
    $("#newTrend").show();
});
});

代码运行良好,但我想在标签更改时添加淡入淡出效果

这是我在 jsfiddle 中的代码http://jsfiddle.net/Ta3Q4/

当我使用 .fadeOut() 和 .fadeIn() 而不是 .hide() 和 .show() 时

新标签和趋势标签同时显示,看这里http://jsfiddle.net/Ta3Q4/1/我的意思

那么如何在不同时显示两个标签的情况下进行淡入淡出呢?

【问题讨论】:

    标签: jquery


    【解决方案1】:

    使用fadeOut 回调:

    $(function() {
        $("#t1").click(function() {
    
            $("#t2").removeClass("current");
            $(this).addClass("current");
            $("#newTrend").fadeOut(400, function() {            
                $("#newContent").fadeIn(400);
            });
    
        });
        $("#t2").click(function() {
    
            $("#t1").removeClass("current");
            $(this).addClass("current");
            $("#newContent").fadeOut(400, function() {           
                $("#newTrend").fadeIn(400);
            });     
        });
    });
    

    这样,在旧元素完全淡出之前,您不会淡入新元素。

    Updated fiddle.

    【讨论】:

      【解决方案2】:
      $(function() {
          $("#t1").click(function() {
              $("#t2").removeClass("current");
              $(this).addClass("current");
              $("#newTrend").fadeOut('slow',function() {
                  $("#newContent").fadeIn();
                      });
          });
          $("#t2").click(function() {
              $("#t1").removeClass("current");
              $(this).addClass("current");
              $("#newContent").fadeOut('slow',function() {
                  $("#newTrend").fadeIn();
                      });
          });
      });
      

      【讨论】:

        【解决方案3】:

        fadeIn() 添加为fadeOut 的回调。

        $("#newContent").fadeOut(function() {
            $("#newTrend").fadeIn();   
        });
        
        $("#newTrend").fadeOut(function() {
            $("#newContent").fadeIn();
        });
        

        演示:http://jsfiddle.net/Ta3Q4/6/

        【讨论】:

          最近更新 更多