Skip to content

第10章:基础实战(新手必练,逐个突破)

实战1:页面元素交互(DOM+事件基础)

10.1 需求分析:实现按钮控制元素显示/隐藏、修改样式

需求:创建一个页面,包含一个按钮和一个盒子,点击按钮可以控制盒子的显示/隐藏,并在显示时修改盒子的样式。

10.2 核心实现:选择器、事件绑定、CSS样式操作

核心知识点

  • jQuery选择器
  • 事件绑定
  • CSS样式操作
  • 显示/隐藏方法

10.3 实操代码讲解与优化

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>页面元素交互</title>
    <style>
        .container { 
            width: 400px; 
            margin: 20px auto;
            padding: 20px;
            border: 1px solid #ccc;
        }
        .box { 
            width: 200px; 
            height: 200px; 
            background-color: #f0f0f0;
            border: 1px solid #ddd;
            margin: 20px 0;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 18px;
        }
        .box.active { 
            background-color: yellow;
            border-color: orange;
            font-weight: bold;
        }
        button { 
            padding: 10px 20px;
            cursor: pointer;
        }
    </style>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <div class="container">
        <h2>页面元素交互</h2>
        <button id="toggleBtn">切换显示/隐藏</button>
        <div class="box" id="myBox">Hello jQuery</div>
    </div>
    
    <script>
        $(document).ready(function() {
            // 绑定点击事件
            $('#toggleBtn').click(function() {
                // 切换盒子的显示/隐藏
                $('#myBox').toggle('slow', function() {
                    // 动画完成后的回调
                    if ($(this).is(':visible')) {
                        // 如果显示,添加active类
                        $(this).addClass('active').text('Hello jQuery (已显示)');
                    } else {
                        // 如果隐藏,移除active类
                        $(this).removeClass('active').text('Hello jQuery');
                    }
                });
            });
        });
    </script>
</body>
</html>

代码解析:

  1. 选择器:使用$('#toggleBtn')$('#myBox')选择元素
  2. 事件绑定:使用.click()方法绑定点击事件
  3. 显示/隐藏:使用.toggle()方法切换元素的显示/隐藏状态
  4. 样式操作:使用.addClass().removeClass()方法修改元素样式
  5. 回调函数:在动画完成后执行回调函数,根据元素状态修改文本内容

优化建议:

  • 添加更多交互效果,如鼠标悬停效果
  • 使用CSS过渡动画代替jQuery动画,提升性能
  • 添加多个盒子,实现批量操作

实战2:表单验证(表单事件+DOM操作)

10.4 需求分析:验证表单输入(用户名、密码、邮箱格式),阻止非法提交

需求:创建一个登录表单,验证用户名、密码和邮箱的输入,阻止非法提交,并显示错误提示。

10.5 核心实现:表单事件、val()获取值、正则表达式、事件阻止

核心知识点

  • 表单事件(submit、focus、blur)
  • val()方法获取表单值
  • 正则表达式验证
  • 事件阻止(event.preventDefault())
  • DOM操作显示错误信息

10.6 实操:实现实时验证、提交验证,提示错误信息

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>表单验证</title>
    <style>
        .container { 
            width: 400px; 
            margin: 20px auto;
            padding: 20px;
            border: 1px solid #ccc;
        }
        form { 
            margin: 20px 0;
        }
        .form-group { 
            margin: 10px 0;
        }
        label { 
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input { 
            width: 100%;
            padding: 8px;
            box-sizing: border-box;
        }
        .error { 
            color: red;
            font-size: 12px;
            margin-top: 5px;
            display: none;
        }
        button { 
            padding: 10px 20px;
            cursor: pointer;
            margin-top: 10px;
        }
        .success { 
            color: green;
            margin-top: 10px;
            display: none;
        }
    </style>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <div class="container">
        <h2>表单验证</h2>
        <form id="loginForm">
            <div class="form-group">
                <label for="username">用户名</label>
                <input type="text" id="username" name="username">
                <div class="error" id="usernameError">用户名不能为空</div>
            </div>
            <div class="form-group">
                <label for="password">密码</label>
                <input type="password" id="password" name="password">
                <div class="error" id="passwordError">密码长度不能少于6位</div>
            </div>
            <div class="form-group">
                <label for="email">邮箱</label>
                <input type="email" id="email" name="email">
                <div class="error" id="emailError">请输入有效的邮箱地址</div>
            </div>
            <button type="submit">登录</button>
            <div class="success" id="successMsg">登录成功!</div>
        </form>
    </div>
    
    <script>
        $(document).ready(function() {
            // 实时验证
            $('#username').blur(function() {
                const username = $(this).val();
                if (username === '') {
                    $('#usernameError').show();
                } else {
                    $('#usernameError').hide();
                }
            });
            
            $('#password').blur(function() {
                const password = $(this).val();
                if (password.length < 6) {
                    $('#passwordError').show();
                } else {
                    $('#passwordError').hide();
                }
            });
            
            $('#email').blur(function() {
                const email = $(this).val();
                const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                if (!emailRegex.test(email)) {
                    $('#emailError').show();
                } else {
                    $('#emailError').hide();
                }
            });
            
            // 表单提交验证
            $('#loginForm').submit(function(event) {
                event.preventDefault();
                
                let isValid = true;
                
                // 验证用户名
                const username = $('#username').val();
                if (username === '') {
                    $('#usernameError').show();
                    isValid = false;
                } else {
                    $('#usernameError').hide();
                }
                
                // 验证密码
                const password = $('#password').val();
                if (password.length < 6) {
                    $('#passwordError').show();
                    isValid = false;
                } else {
                    $('#passwordError').hide();
                }
                
                // 验证邮箱
                const email = $('#email').val();
                const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                if (!emailRegex.test(email)) {
                    $('#emailError').show();
                    isValid = false;
                } else {
                    $('#emailError').hide();
                }
                
                // 提交表单
                if (isValid) {
                    $('#successMsg').show();
                    // 模拟表单提交
                    setTimeout(() => {
                        $('#successMsg').hide();
                        alert('登录成功,即将跳转到首页');
                    }, 1000);
                }
            });
        });
    </script>
</body>
</html>

代码解析:

  1. 实时验证:使用blur事件在输入框失去焦点时进行验证
  2. 表单提交验证:使用submit事件在表单提交时进行全面验证
  3. 事件阻止:使用event.preventDefault()阻止表单默认提交行为
  4. 正则表达式:使用正则表达式验证邮箱格式
  5. 错误提示:使用.show().hide()方法显示和隐藏错误信息

优化建议:

  • 添加更多验证规则,如密码强度验证
  • 使用更美观的错误提示样式
  • 添加表单提交动画效果
  • 实现表单数据的本地存储

实战3:简单动画效果(动画方法实战)

10.7 需求分析:实现导航栏折叠、元素悬浮动画、淡入淡出效果

需求:创建一个页面,包含导航栏折叠效果、元素悬浮动画和淡入淡出效果。

10.8 核心实现:slideToggle()、fadeIn()、animate() 方法

核心知识点

  • 导航栏折叠:使用slideToggle()方法
  • 元素悬浮:使用mouseentermouseleave事件结合animate()方法
  • 淡入淡出:使用fadeIn()fadeOut()方法

10.9 实操:调试动画时长、顺序,优化用户体验

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>简单动画效果</title>
    <style>
        .container { 
            width: 600px; 
            margin: 20px auto;
            padding: 20px;
            border: 1px solid #ccc;
        }
        .nav { 
            background-color: #333;
            color: white;
            padding: 10px;
            margin: 20px 0;
        }
        .nav-title { 
            cursor: pointer;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .nav-content { 
            background-color: #f0f0f0;
            padding: 10px;
            display: none;
        }
        .nav-content ul { 
            list-style: none;
            padding: 0;
        }
        .nav-content li { 
            margin: 5px 0;
        }
        .nav-content a { 
            color: #333;
            text-decoration: none;
        }
        .hover-box { 
            width: 150px; 
            height: 150px; 
            background-color: blue;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 20px 0;
            cursor: pointer;
        }
        .fade-box { 
            width: 100px; 
            height: 100px; 
            background-color: red;
            margin: 20px 0;
            display: none;
        }
        button { 
            padding: 10px 20px;
            cursor: pointer;
            margin: 5px;
        }
    </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>
                    <li><a href="#">服务项目</a></li>
                </ul>
            </div>
        </div>
        
        <!-- 元素悬浮动画 -->
        <div class="hover-box" id="hoverBox">鼠标悬浮</div>
        
        <!-- 淡入淡出效果 -->
        <div>
            <button id="fadeInBtn">淡入</button>
            <button id="fadeOutBtn">淡出</button>
            <div class="fade-box" id="fadeBox"></div>
        </div>
    </div>
    
    <script>
        $(document).ready(function() {
            // 导航栏折叠
            $('#navTitle').click(function() {
                $('#navContent').slideToggle('slow');
                $(this).find('span:last').text($('#navContent').is(':visible') ? '▲' : '▼');
            });
            
            // 元素悬浮动画
            $('#hoverBox')
                .mouseenter(function() {
                    $(this).animate({
                        width: '200px',
                        height: '200px',
                        fontSize: '24px',
                        backgroundColor: 'green'
                    }, 300);
                })
                .mouseleave(function() {
                    $(this).animate({
                        width: '150px',
                        height: '150px',
                        fontSize: '16px',
                        backgroundColor: 'blue'
                    }, 300);
                });
            
            // 淡入淡出效果
            $('#fadeInBtn').click(function() {
                $('#fadeBox').fadeIn('slow');
            });
            
            $('#fadeOutBtn').click(function() {
                $('#fadeBox').fadeOut('slow');
            });
        });
    </script>
</body>
</html>

代码解析:

  1. 导航栏折叠:使用slideToggle()方法实现折叠效果,结合文本切换箭头图标
  2. 元素悬浮:使用mouseentermouseleave事件触发animate()方法,实现元素大小、字体和颜色的变化
  3. 淡入淡出:使用fadeIn()fadeOut()方法实现元素的淡入淡出效果

优化建议:

  • 添加更多动画效果,如元素旋转、缩放等
  • 优化动画时长,使动画更流畅
  • 添加动画队列控制,避免动画堆积
  • 使用CSS过渡动画代替部分jQuery动画,提升性能

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