返回值:jQueryfadeTo(duration, opacity, [callback])

调整匹配元素的透明度。

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

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

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

比如下面这个页面:

<div id="clickme">
    Click here
  </div>
  <img id="book" src="book.png" alt="" width="100" height="123" />

如果元素一开始是显现的,我们可以缓慢调整它的透明度:

$('#clickme').click(function() {
    $('#book').fadeTo('slow', 0.5, function() {
      // 动画完成
    });
  });
  

如果 duration 参数设置成 0,那么这个方法就仅仅修改 opacity CSS属性。所以 .fadeTo(0, opacity) 等价于 .css('opacity', opacity)

示例:

把第一个段落的透明度渐变成 0.33 (33%,大约三分之一透明度), 用时 600 毫秒。

<!DOCTYPE html>
<html>
<head>
<script src="jquery.min.js"></script>
</head>
<body>

<p>
Click this paragraph to see it fade.
</p>

<p>
Compare to this one that won't fade.
</p>

<script>


$("p:first").click(function () {
$(this).fadeTo("slow", 0.33);
});


</script>
</body>
</html>
演示:

示例:

每次点击后把 div 渐变成随机透明度,用时 200 毫秒。

<!DOCTYPE html>
<html>
<head>
<style>
p { width:80px; margin:0; padding:5px; }
div { width:40px; height:40px; position:absolute; }
div#one { top:0; left:0; background:#f00; }
div#two { top:20px; left:20px; background:#0f0; }
div#three { top:40px; left:40px; background:#00f; }
</style>
<script src="jquery.min.js"></script>
</head>
<body>

<p>And this is the library that John built...</p>

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

<script>


$("div").click(function () {
$(this).fadeTo("fast", Math.random());
});


</script>
</body>
</html>
演示:

示例:

找到正确答案!渐变耗时 250 毫秒,并且在完成后会改变字体样式。

<!DOCTYPE html>
<html>
<head>
<style>
div, p { width:80px; height:40px; top:0; margin:0; 
position:absolute; padding-top:8px; }
p { background:#fcc; text-align:center; }
div { background:blue; }
</style>
<script src="jquery.min.js"></script>
</head>
<body>

<p>Wrong</p>
<div></div>
<p>Wrong</p>
<div></div>

<p>Right!</p>
<div></div>

<script>


var getPos = function (n) {
return (Math.floor(n) * 90) + "px";
};
$("p").each(function (n) {
var r = Math.floor(Math.random() * 3);
var tmp = $(this).text();
$(this).text($("p:eq(" + r + ")").text());
$("p:eq(" + r + ")").text(tmp);
$(this).css("left", getPos(n));
});
$("div").each(function (n) {
      $(this).css("left", getPos(n));
    })
.css("cursor", "pointer")
.click(function () {
      $(this).fadeTo(250, 0.25, function () {
            $(this).css("cursor", "")
                   .prev().css({"font-weight": "bolder",
                                "font-style": "italic"});
          });
    });



</script>
</body>
</html>
演示: