返回值:jQueryfadeIn([duration], [callback])

通过改变透明度将匹配的元素淡入显示。

.fadeIn() 方法对匹配元素的透明度生成动画效果。

duration 参数可以提供一个毫秒数,代表动画运行的时间,时间越长动画越慢。还可以提供字符串 'fast''slow' ,分别对应了 200600 毫秒。如果没有设置 duration 参数,或者设置成其他无法识别的字符串,就会使用默认值 400 毫秒。

我们可以对任何元素应用动画,比如下面这个例子,对图片应用动画:

<div id="clickme">
      Click here
    </div>
    <img id="book" src="book.png" alt="" width="100" height="123" />
    With the element initially hidden, we can show it slowly:
    $('#clickme').click(function() {
      $('#book').fadeIn('slow', function() {
        // Animation complete
      });
    });

缓冲函数

从 jQuery 1.4.3 起,增加了一个可选的参数,用于确定使用的缓冲函数。缓冲函数确定了动画在不同位置的速度。jQuery默认只提供两个缓冲效果:swing(默认值) 和 线性缓冲效果linear。更多特效需要使用插件。可以访问 jQuery UI 网站 来获得更多信息。

回调函数

如果提供了回调函数,那么当动画结束时,会调用这个函数。通常用来按顺序执行一组不同的动画。这个函数不接受任何参数,但是 this 会设成将要执行动画的那个元素。如果对多个元素设置动画,那么要非常注意,回调函数会在每一个元素执行完动画后都执行一次,而不是这组动画整体才执行一次。

截止 jQuery 1.6, .promise() 方法可以和 deferred.done() 方法一起使用,用于当所有匹配的元素执行完各自的动画后,再调用一个回调函数。 ( 参见 .promise() 例子 )。

补充说明:

  • 所有的 jQuery 动画, 包括 .fadeIn(), 都可以被关闭,通过全局设置 jQuery.fx.off = true, 效果等同于将动画时间 duration 设置成 0. 可以访问 jQuery.fx.off 来获得更多信息。
  • 由于 requestAnimationFrame() 特性的原因,绝对不要在 setIntervalsetTimeout 方法中设置动画队列。 为了保护CPU资源, 支持 requestAnimationFrame 的浏览器在当前窗口或标签失去焦点时,是不更新动画的。如果你通过 setIntervalsetTimeout 方法在动画暂停时,持续向队列里添加动画,那么在窗口或标签重新获得焦点时,所有在队列中的动画都会被播放。 为了避免这个潜在的问题,可以在循环时,利用最后一个动画的回调函数,或者给元素添加 .queue() 方法来避免这个问题,实现动画的继续播放。

示例:

依次把隐藏的 div 以淡入方式显现出来,用时 600 毫秒。

<!DOCTYPE html>
<html>
<head>
<style>
    span { color:red; cursor:pointer; }
    div { margin:3px; width:80px; display:none;
      height:80px; float:left; }
      div#one { background:#f00; }
      div#two { background:#0f0; }
      div#three { background:#00f; }
    </style>
<script src="jquery.min.js"></script>
</head>
<body>

<span>Click here...</span>

    <div id="one"></div>
    <div id="two"></div>
    <div id="three"></div>

<script>


      $(document.body).click(function () {
        $("div:hidden:first").fadeIn("slow");
      });
    

</script>
</body>
</html>

演示:

示例:

在文本上方渐渐显示出一个红色方块。动画完成后,马上再以淡入方式在上面再显示一行文本。

<!DOCTYPE html>
<html>
<head>
<style>
      p { position:relative; width:400px; height:90px; }
      div { position:absolute; width:400px; height:65px; 
        font-size:36px; text-align:center; 
        color:yellow; background:red;
        padding-top:25px; 
        top:0; left:0; display:none; }
        span { display:none; }
      </style>
<script src="jquery.min.js"></script>
</head>
<body>

<p>
        Let it be known that the party of the first part
        and the party of the second part are henceforth
        and hereto directed to assess the allegations
        for factual correctness... (<a href="#">click!</a>)
        <div><span>CENSORED!</span></div>

      </p>

<script>


        $("a").click(function () {
          $("div").fadeIn(3000, function () {
            $("span").fadeIn(100);
          });
          return false;
        }); 

      

</script>
</body>
</html>

演示: