In the previous section, we learned how to display and hide elements. In this section, we will learn how to achieve the fade-in and fade-out effect of elements.
fadeIn() method
fadeIn()
method is used to fade in hidden elements.
The syntax is as follows:
$(selector).fadeIn(speed,callback);
speed
: Specifies the duration of the effect. The optional values areslow
,fast
or milliseconds.callback
: isfading
function name after the completion of the execution.
Example:
For example, when we click the button, set the purple square as a fade-in effect:
<!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>
Demonstration effect in the browser:
We can achieve different fade-in effects fadeIn()
$(".rect").fadeIn("fast");
Demonstration effect in the browser:
fadeOut() method
fadeOut()
method has the fadeIn()
method, which is used to fade out visible elements.
The syntax is as follows:
$(selector).fadeOut(speed,callback);
Example:
<!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>
Demonstration effect in the browser:
fadeToggle() method
fadeToggle()
method can be switched between the fadeIn()
and fadeOut()
The syntax is as follows:
$(selector).fadetoogle(speed,callback);
If the element has faded out, the fadeToggle()
method will add a fade-in effect to the element. If the element has faded in, the fadeToggle()
method will add a fade out effect to the element.
Example:
To achieve a fade-in and fade-out switching effect:
$(function(){
$("button").click(function(){
$(".rect").fadeToggle(2000);
});
});
Demonstration effect in the browser:
fadeTo() method
fadeTo()
method allows the gradient to be a given opacity, with a value between 0 and 1.
The syntax is as follows:
$(selector).fadeTo(speed,opacity,callback);
The parameter opacity
is a required parameter, which is used to set the fade-in and fade-out effect to a given opacity, and the other two parameters are optional parameters.
Example:
For example, we change the transparency of this square to 0.5
:
$(function(){
$("button").click(function(){
$(".rect").fadeTo(2000, 0.5);
});
});
Demonstration effect in the browser:
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。