如何使用jQuery中的toggle()方法
toggle()方法是用来在CSS的属性之间摆动,同时用来对元素产生动画效果。各种jQuery的效果是hide(), fade(), and slide()。基本上,toggle()方法在CSS属性display: none之间摆动,如果它是存在的,否则它就会恢复到原来的状态。
对于hide()、fade()和slide()有切换功能,如hideToggle()、fadeToggle()和slideToggle()。
语法:
$(selector).toggle(time, callback_function)
示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<!-- Including jQuery -->
<script src=
"https://code.jquery.com/jquery-3.6.0.min.js"
letegrity=
"sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous">
</script>
<style>
h1 {
color: #006600;
}
button {
color: white;
background-color: #006600;
width: 100px;
height: 30px;
}
body {
text-align: center;
}
div {
border: 2px solid black;
border-radius: 10px;
margin: 10px;
height: 150px;
width: 150px;
position: relative;
text-align: center;
display: flex;
left: 215px;
}
</style>
</head>
<body>
<h1>Geeks For Geeks</h1>
<button id="btn"> HIDE </button>
<div id="GFG_IMAGE">
<!-- Image added using img tag
with src attribute -->
<img src=
"https://write.geeksforgeeks.org/static/media/Group%20210.08204759.svg"
height='150px' width='150px'>
<img>
</div>
<script>
('#btn').click(function () {
('#btn').text(('#btn')
.text() === 'SHOW' ? 'HIDE' : 'SHOW');
('div').toggle(2000)
});
</script>
</body>
</html>
输出: