1

jQuery 实现淡入淡出效果

 2 years ago
source link: https://segmentfault.com/a/1190000040829971
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

jQuery 实现淡入淡出效果

上一节我们学习了如何实现元素的显示与隐藏,本节我们来学习如何实现元素的淡入淡出效果。

fadeIn()方法

fadeIn() 方法用于淡入已隐藏的元素。

语法如下所示:

$(selector).fadeIn(speed,callback);
  • speed:规定效果的时长,可选值有 slowfast 或毫秒。
  • callback:是 fading 完成后所执行的函数名称。

例如当我们点击按钮时,将紫色正方形设置为淡入效果:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery_侠课岛(9xkd.com)</title>
<script src="jquery-3.5.1.min.js"></script>
<script>
  $(function(){
    $("button").click(function(){
      $(".rect").fadeIn(2000);
    });
  });
</script>
</head>
<body>
  <div>
    <div style="margin-bottom: 20px;"><button>淡入效果</button></div>
    <div class="rect" style="width:150px;height:150px;background:plum;display: none;"></div>
  </div>
</body>
</html>

在浏览器中的演示效果:

我们可以通过设置 fadeIn() 方法的参数来实现不同的淡入效果,例如:

$(".rect").fadeIn("fast");

在浏览器中的演示效果:

fadeOut()方法

fadeOut() 方法与 fadeIn() 方法效果刚好相反,用于淡出可见元素。

语法如下所示:

$(selector).fadeOut(speed,callback);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery_侠课岛(9xkd.com)</title>
<script src="jquery-3.5.1.min.js"></script>
<script>
  $(function(){
    $("button").click(function(){
      $(".rect").fadeOut(2000);
    });
  });
</script>
</head>
<body>
  <div>
    <div style="margin-bottom: 20px;"><button>淡出效果</button></div>
    <div class="rect" style="width:150px;height:150px;background:plum;"></div>
  </div>
</body>
</html>

在浏览器中的演示效果:

fadeToggle()方法

fadeToggle() 方法可以在 fadeIn()fadeOut() 方法之间进行切换。

语法如下:

$(selector).fadetoogle(speed,callback);

如果元素已淡出,则 fadeToggle() 方法会向元素添加淡入效果。如果元素已经淡入,fadeToggle() 方法会向元素添加淡出效果。

实现一个淡入淡出切换效果:

$(function(){
    $("button").click(function(){
      $(".rect").fadeToggle(2000);
    });
});

在浏览器的演示效果:

fadeTo()方法

fadeTo() 方法允许渐变为给定的不透明度,值介于 0 与 1 之间。

语法如下:

$(selector).fadeTo(speed,opacity,callback);

其中参数 opacity 是必须参数,用于将淡入淡出效果设置为给定的不透明度,其他两个参数为可选参数。

例如我们将这个正方形的透明度改为 0.5

$(function(){
    $("button").click(function(){
      $(".rect").fadeTo(2000, 0.5);
    });
});

在浏览器中的演示效果:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK