Skip to content

第7章:jQuery 动画效果(提升页面体验)

7.1 基础动画(简单易用,常用)

show()/hide():显示/隐藏元素(无动画/有动画)

  • 作用:显示或隐藏元素,可选择是否使用动画效果

  • 语法

    • 无动画:$(selector).show() / $(selector).hide()
    • 有动画:$(selector).show(speed, callback) / $(selector).hide(speed, callback)
  • 参数

    • speed:动画速度,可选值:'slow'、'fast' 或毫秒数
    • callback:动画完成后的回调函数
  • 示例

    javascript
    // 无动画显示/隐藏
    $('#btn1').click(function() {
        $('#element').show();
    });
    
    $('#btn2').click(function() {
        $('#element').hide();
    });
    
    // 有动画显示/隐藏
    $('#btn3').click(function() {
        $('#element').show('slow', function() {
            alert('元素已显示');
        });
    });

toggle():切换元素显示/隐藏状态

  • 作用:切换元素的显示/隐藏状态
  • 语法$(selector).toggle(speed, callback)
  • 示例
    javascript
    // 切换元素显示/隐藏
    $('#btn').click(function() {
        $('#element').toggle('fast');
    });

slideDown()/slideUp():下滑/上滑动画(折叠效果)

  • 作用:通过改变元素的高度来显示或隐藏元素
  • 语法$(selector).slideDown(speed, callback) / $(selector).slideUp(speed, callback)
  • 示例
    javascript
    // 下滑显示
    $('#btn1').click(function() {
        $('#element').slideDown('slow');
    });
    
    // 上滑隐藏
    $('#btn2').click(function() {
        $('#element').slideUp('fast');
    });

slideToggle():切换下滑/上滑动画

  • 作用:切换元素的下滑/上滑状态
  • 语法$(selector).slideToggle(speed, callback)
  • 示例
    javascript
    // 切换下滑/上滑
    $('#btn').click(function() {
        $('#element').slideToggle('slow');
    });

fadeIn()/fadeOut():淡入/淡出动画(透明度变化)

  • 作用:通过改变元素的透明度来显示或隐藏元素
  • 语法$(selector).fadeIn(speed, callback) / $(selector).fadeOut(speed, callback)
  • 示例
    javascript
    // 淡入显示
    $('#btn1').click(function() {
        $('#element').fadeIn('slow');
    });
    
    // 淡出隐藏
    $('#btn2').click(function() {
        $('#element').fadeOut('fast');
    });

fadeToggle():切换淡入/淡出动画

  • 作用:切换元素的淡入/淡出状态
  • 语法$(selector).fadeToggle(speed, callback)
  • 示例
    javascript
    // 切换淡入/淡出
    $('#btn').click(function() {
        $('#element').fadeToggle('slow');
    });

7.2 自定义动画(animate() 方法,灵活控制动画)

animate() 语法结构(目标样式、动画时长、回调函数)

  • 作用:创建自定义动画效果

  • 语法$(selector).animate(properties, speed, easing, callback)

  • 参数

    • properties:要动画的CSS属性和目标值
    • speed:动画速度,可选值:'slow'、'fast' 或毫秒数
    • easing:动画缓动函数,默认值:'swing'
    • callback:动画完成后的回调函数

实操:实现元素移动、缩放、透明度变化等自定义动画

示例1:元素移动

javascript
// 元素向右移动200px
$('#btn1').click(function() {
    $('#box').animate({ left: '200px' }, 1000);
});

// 元素向上移动100px
$('#btn2').click(function() {
    $('#box').animate({ top: '-100px' }, 1000);
});

示例2:元素缩放

javascript
// 元素放大
$('#btn1').click(function() {
    $('#box').animate({
        width: '300px',
        height: '300px',
        fontSize: '24px'
    }, 1000);
});

// 元素缩小
$('#btn2').click(function() {
    $('#box').animate({
        width: '100px',
        height: '100px',
        fontSize: '12px'
    }, 1000);
});

示例3:透明度变化

javascript
// 元素逐渐变透明
$('#btn1').click(function() {
    $('#box').animate({ opacity: '0.5' }, 1000);
});

// 元素逐渐变不透明
$('#btn2').click(function() {
    $('#box').animate({ opacity: '1' }, 1000);
});

示例4:链式动画

javascript
// 链式动画
$('#btn').click(function() {
    $('#box')
        .animate({ left: '200px' }, 1000)
        .animate({ top: '100px' }, 1000)
        .animate({ width: '200px' }, 1000)
        .animate({ height: '200px' }, 1000);
});

7.3 动画停止与延迟(stop()、delay() 方法)

stop():停止当前动画

  • 作用:停止元素当前正在执行的动画

  • 语法

    • 停止当前动画:$(selector).stop()
    • 停止所有动画:$(selector).stop(true)
    • 停止所有动画并跳转到最终状态:$(selector).stop(true, true)
  • 示例

    javascript
    // 开始动画
    $('#startBtn').click(function() {
        $('#box').animate({ left: '500px' }, 3000);
    });
    
    // 停止动画
    $('#stopBtn').click(function() {
        $('#box').stop();
    });

delay():延迟动画

  • 作用:延迟执行后续动画

  • 语法$(selector).delay(duration)

  • 参数

    • duration:延迟时间,单位为毫秒
  • 示例

    javascript
    // 延迟动画
    $('#btn').click(function() {
        $('#box')
            .animate({ left: '200px' }, 1000)
            .delay(1000) // 延迟1秒
            .animate({ top: '100px' }, 1000);
    });

7.4 实操案例:实现导航栏折叠、轮播图基础动画、元素悬浮效果

案例:动画效果练习

HTML结构:

html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery动画效果练习</title>
    <style>
        .container { 
            width: 600px; 
            margin: 20px auto;
            padding: 20px;
            border: 1px solid #ccc;
        }
        .nav { 
            background-color: #333;
            color: white;
            padding: 10px;
        }
        .nav-title { 
            cursor: pointer;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .nav-content { 
            background-color: #f0f0f0;
            padding: 10px;
            display: none;
        }
        .box { 
            width: 100px;
            height: 100px;
            background-color: red;
            position: relative;
            margin: 20px 0;
        }
        .carousel { 
            width: 400px;
            height: 200px;
            position: relative;
            overflow: hidden;
            margin: 20px 0;
        }
        .carousel-item { 
            width: 400px;
            height: 200px;
            position: absolute;
            top: 0;
            left: 0;
            display: none;
        }
        .carousel-item.active { 
            display: block;
        }
        .carousel-indicators { 
            position: absolute;
            bottom: 10px;
            left: 50%;
            transform: translateX(-50%);
        }
        .indicator { 
            width: 10px;
            height: 10px;
            border-radius: 50%;
            background-color: rgba(255,255,255,0.5);
            display: inline-block;
            margin: 0 5px;
            cursor: pointer;
        }
        .indicator.active { 
            background-color: white;
        }
        .hover-box { 
            width: 150px;
            height: 150px;
            background-color: blue;
            color: white;
            text-align: center;
            line-height: 150px;
            margin: 20px 0;
            cursor: pointer;
        }
        button { 
            padding: 5px 10px;
            margin: 5px;
            cursor: pointer;
        }
    </style>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <div class="container">
        <h2>动画效果练习</h2>
        
        <!-- 导航栏折叠 -->
        <div class="nav">
            <div class="nav-title" id="navTitle">
                <span>导航菜单</span>
                <span>▼</span>
            </div>
            <div class="nav-content" id="navContent">
                <ul>
                    <li><a href="#">首页</a></li>
                    <li><a href="#">关于我们</a></li>
                    <li><a href="#">联系我们</a></li>
                </ul>
            </div>
        </div>
        
        <!-- 元素移动 -->
        <div>
            <button id="moveBtn">移动元素</button>
            <button id="resetBtn">重置位置</button>
            <div class="box" id="moveBox"></div>
        </div>
        
        <!-- 轮播图 -->
        <div class="carousel" id="carousel">
            <div class="carousel-item active" style="background-color: red;">幻灯片1</div>
            <div class="carousel-item" style="background-color: green;">幻灯片2</div>
            <div class="carousel-item" style="background-color: blue;">幻灯片3</div>
            <div class="carousel-indicators">
                <span class="indicator active" data-index="0"></span>
                <span class="indicator" data-index="1"></span>
                <span class="indicator" data-index="2"></span>
            </div>
        </div>
        
        <!-- 元素悬浮效果 -->
        <div class="hover-box" id="hoverBox">鼠标悬浮</div>
    </div>
    
    <script>
        $(document).ready(function() {
            // 导航栏折叠
            $('#navTitle').click(function() {
                $('#navContent').slideToggle('slow');
                $(this).find('span:last').text($('#navContent').is(':visible') ? '▲' : '▼');
            });
            
            // 元素移动
            $('#moveBtn').click(function() {
                $('#moveBox').animate({ left: '400px' }, 1000);
            });
            
            $('#resetBtn').click(function() {
                $('#moveBox').animate({ left: '0' }, 500);
            });
            
            // 轮播图
            let currentIndex = 0;
            const itemCount = $('.carousel-item').length;
            
            function showSlide(index) {
                $('.carousel-item').fadeOut('slow').removeClass('active');
                $('.carousel-item').eq(index).fadeIn('slow').addClass('active');
                $('.indicator').removeClass('active');
                $('.indicator').eq(index).addClass('active');
                currentIndex = index;
            }
            
            // 自动轮播
            setInterval(function() {
                let nextIndex = (currentIndex + 1) % itemCount;
                showSlide(nextIndex);
            }, 3000);
            
            // 点击指示器
            $('.indicator').click(function() {
                const index = $(this).data('index');
                showSlide(index);
            });
            
            // 元素悬浮效果
            $('#hoverBox')
                .mouseenter(function() {
                    $(this).animate({
                        width: '200px',
                        height: '200px',
                        fontSize: '24px'
                    }, 300);
                })
                .mouseleave(function() {
                    $(this).animate({
                        width: '150px',
                        height: '150px',
                        fontSize: '16px'
                    }, 300);
                });
        });
    </script>
</body>
</html>

测试步骤:

  1. 保存文件为animation-practice.html
  2. 用浏览器打开该文件
  3. 点击导航菜单标题,测试折叠效果
  4. 点击"移动元素"按钮,测试元素移动动画
  5. 观察轮播图自动播放效果,点击指示器切换幻灯片
  6. 将鼠标悬浮在"鼠标悬浮"盒子上,测试悬浮动画效果

案例解析:

  • 导航栏折叠:使用slideToggle()方法实现折叠效果
  • 元素移动:使用animate()方法实现元素移动
  • 轮播图:使用fadeIn()fadeOut()方法实现淡入淡出效果,结合setInterval()实现自动轮播
  • 元素悬浮:使用mouseentermouseleave事件结合animate()方法实现悬浮效果

新手易错点:

  1. 动画队列

    • jQuery会将动画操作加入队列,依次执行
    • 使用stop()方法可以停止当前动画
  2. CSS属性

    • animate()方法中,CSS属性使用驼峰命名法
    • 不是所有CSS属性都支持动画,如background-color(在现代浏览器中支持)
  3. 定位

    • 要使用animate()方法移动元素,元素需要设置position: relativeposition: absolute
  4. 性能考虑

    • 避免在短时间内执行大量动画
    • 使用requestAnimationFrame或CSS动画代替复杂的jQuery动画(在现代浏览器中)
  5. 回调函数

    • 动画完成后的回调函数会在所有匹配元素的动画都完成后执行

© 2026 编程马·菜鸟教程 版权所有