表单基础

表单概述

表单是网页中用于收集用户输入数据的重要元素,广泛应用于登录、注册、搜索、评论等场景。

东巴文(db-w.cn) 认为:表单是用户与网站交互的核心桥梁,设计良好的表单能显著提升用户体验。

表单标签

<form>标签

<form>标签用于创建HTML表单:

<form action="/submit" method="post">
    <!-- 表单元素 -->
</form>

东巴文form标签属性:

属性 说明 是否必需
action 提交地址 可选
method 提交方法 推荐
enctype 编码类型 可选
name 表单名称 可选
target 提交目标 可选
autocomplete 自动完成 可选
novalidate 禁用验证 可选

提交方法

东巴文HTTP方法对比:

方法 说明 数据位置 使用场景
GET 获取数据 URL参数 搜索、筛选
POST 提交数据 请求体 登录、注册、上传
<!-- GET方法 -->
<form action="/search" method="get">
    <input type="text" name="q">
    <button type="submit">搜索</button>
</form>

<!-- POST方法 -->
<form action="/login" method="post">
    <input type="text" name="username">
    <input type="password" name="password">
    <button type="submit">登录</button>
</form>

编码类型

东巴文enctype属性值:

属性值 说明 使用场景
application/x-www-form-urlencoded 默认,URL编码 普通表单
multipart/form-data 多部分表单数据 文件上传
text/plain 纯文本 调试
<!-- 文件上传 -->
<form action="/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <button type="submit">上传</button>
</form>

输入元素

<input>标签

<input>标签是最常用的表单元素:

<input type="text" name="username">

东巴文input标签属性:

属性 说明 是否必需
type 输入类型 必需
name 名称 必需
value 值 可选
placeholder 占位符 推荐
required 必填 可选
disabled 禁用 可选
readonly 只读 可选
maxlength 最大长度 可选
minlength 最小长度 可选
pattern 正则验证 可选
autocomplete 自动完成 可选
autofocus 自动聚焦 可选

输入类型

东巴文input类型分类:

文本输入类

<!-- 单行文本 -->
<input type="text" name="username" placeholder="请输入用户名">

<!-- 密码 -->
<input type="password" name="password" placeholder="请输入密码">

<!-- 邮箱 -->
<input type="email" name="email" placeholder="请输入邮箱">

<!-- 搜索框 -->
<input type="search" name="q" placeholder="搜索...">

<!-- 电话 -->
<input type="tel" name="phone" placeholder="请输入电话号码">

<!-- URL -->
<input type="url" name="website" placeholder="请输入网址">

数字输入类

<!-- 数字 -->
<input type="number" name="age" min="0" max="120" step="1">

<!-- 范围滑块 -->
<input type="range" name="volume" min="0" max="100" value="50">

<!-- 日期 -->
<input type="date" name="birthday">

<!-- 时间 -->
<input type="time" name="appointment">

<!-- 日期时间 -->
<input type="datetime-local" name="meeting">

<!-- 月份 -->
<input type="month" name="month">

<!-- 周 -->
<input type="week" name="week">

选择输入类

<!-- 复选框 -->
<input type="checkbox" name="hobby" value="reading"> 阅读
<input type="checkbox" name="hobby" value="music"> 音乐

<!-- 单选按钮 -->
<input type="radio" name="gender" value="male"> 男
<input type="radio" name="gender" value="female"> 女

<!-- 颜色选择器 -->
<input type="color" name="color" value="#ff0000">

<!-- 文件选择 -->
<input type="file" name="file">

其他类型

<!-- 隐藏字段 -->
<input type="hidden" name="token" value="abc123">

<!-- 提交按钮 -->
<input type="submit" value="提交">

<!-- 重置按钮 -->
<input type="reset" value="重置">

<!-- 普通按钮 -->
<input type="button" value="按钮">

<!-- 图像按钮 -->
<input type="image" src="submit.png" alt="提交">

其他表单元素

<textarea>标签

多行文本输入框:

<textarea name="message" rows="4" cols="50" placeholder="请输入留言">
</textarea>

东巴文textarea属性:

属性 说明 示例
rows 可见行数 rows="4"
cols 可见列数 cols="50"
placeholder 占位符 placeholder="请输入..."
maxlength 最大长度 maxlength="500"
wrap 换行方式 wrap="hard" 或 soft

<select>和<option>

下拉选择框:

<select name="city">
    <option value="">请选择城市</option>
    <option value="beijing">北京</option>
    <option value="shanghai">上海</option>
    <option value="guangzhou">广州</option>
</select>

东巴文select属性:

属性 说明 示例
multiple 多选 multiple
size 可见选项数 size="4"

东巴文option属性:

属性 说明 示例
value 选项值 value="beijing"
selected 默认选中 selected
disabled 禁用 disabled

<optgroup>

选项分组:

<select name="city">
    <optgroup label="直辖市">
        <option value="beijing">北京</option>
        <option value="shanghai">上海</option>
    </optgroup>
    <optgroup label="省会城市">
        <option value="guangzhou">广州</option>
        <option value="chengdu">成都</option>
    </optgroup>
</select>

<button>标签

按钮元素:

<!-- 提交按钮 -->
<button type="submit">提交</button>

<!-- 重置按钮 -->
<button type="reset">重置</button>

<!-- 普通按钮 -->
<button type="button">按钮</button>

<!-- 带图标的按钮 -->
<button type="submit">
    <img src="icon.png" alt=""> 提交
</button>

<label>标签

标签元素,用于关联表单控件:

<!-- 方式1:包裹 -->
<label>
    用户名:<input type="text" name="username">
</label>

<!-- 方式2:for属性 -->
<label for="username">用户名:</label>
<input type="text" id="username" name="username">

东巴文提示:

  • 使用<label>可以提升可访问性
  • 点击标签文本可以聚焦对应的输入框
  • 推荐使用for属性关联

<fieldset>和<legend>

表单分组:

<fieldset>
    <legend>个人信息</legend>
    <label>
        姓名:<input type="text" name="name">
    </label>
    <label>
        年龄:<input type="number" name="age">
    </label>
</fieldset>

<fieldset>
    <legend>联系方式</legend>
    <label>
        电话:<input type="tel" name="phone">
    </label>
    <label>
        邮箱:<input type="email" name="email">
    </label>
</fieldset>

表单验证

HTML5验证属性

东巴文验证属性:

属性 说明 示例
required 必填 required
pattern 正则表达式 pattern="[0-9]{11}"
min 最小值 min="0"
max 最大值 max="100"
minlength 最小长度 minlength="6"
maxlength 最大长度 maxlength="20"
type 类型验证 type="email"

验证示例

<form>
    <!-- 必填 -->
    <input type="text" name="username" required>
    
    <!-- 邮箱格式 -->
    <input type="email" name="email" required>
    
    <!-- 手机号格式 -->
    <input type="tel" name="phone" pattern="[0-9]{11}" required>
    
    <!-- 密码长度 -->
    <input type="password" name="password" minlength="6" maxlength="20" required>
    
    <!-- 年龄范围 -->
    <input type="number" name="age" min="1" max="120" required>
    
    <!-- 网址格式 -->
    <input type="url" name="website">
    
    <button type="submit">提交</button>
</form>

自定义验证消息

<form>
    <input type="text" 
           name="username" 
           required
           minlength="3"
           maxlength="20"
           oninput="setCustomValidity('')"
           oninvalid="setCustomValidity('用户名必须是3-20个字符')">
    
    <input type="password" 
           name="password"
           required
           pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}"
           oninput="setCustomValidity('')"
           oninvalid="setCustomValidity('密码必须包含大小写字母和数字,至少8位')">
    
    <button type="submit">提交</button>
</form>

表单样式

CSS表单样式

<style>
    form {
        max-width: 500px;
        margin: 0 auto;
    }
    
    .form-group {
        margin-bottom: 15px;
    }
    
    label {
        display: block;
        margin-bottom: 5px;
        font-weight: bold;
    }
    
    input[type="text"],
    input[type="email"],
    input[type="password"],
    textarea,
    select {
        width: 100%;
        padding: 10px;
        border: 1px solid #ddd;
        border-radius: 4px;
        font-size: 14px;
        box-sizing: border-box;
    }
    
    input:focus,
    textarea:focus,
    select:focus {
        outline: none;
        border-color: #4CAF50;
        box-shadow: 0 0 5px rgba(76, 175, 80, 0.3);
    }
    
    input:invalid {
        border-color: #f44336;
    }
    
    input:valid {
        border-color: #4CAF50;
    }
    
    button {
        padding: 10px 20px;
        background: #4CAF50;
        color: white;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        font-size: 16px;
    }
    
    button:hover {
        background: #45a049;
    }
    
    .error-message {
        color: #f44336;
        font-size: 12px;
        margin-top: 5px;
    }
</style>

<form>
    <div class="form-group">
        <label for="username">用户名</label>
        <input type="text" id="username" name="username" required>
    </div>
    
    <div class="form-group">
        <label for="email">邮箱</label>
        <input type="email" id="email" name="email" required>
    </div>
    
    <div class="form-group">
        <label for="password">密码</label>
        <input type="password" id="password" name="password" required>
    </div>
    
    <button type="submit">提交</button>
</form>

表单最佳实践

东巴文表单法则

法则1:使用语义化标签

<!-- ✅ 推荐:使用label关联 -->
<label for="username">用户名:</label>
<input type="text" id="username" name="username">

<!-- ❌ 不推荐:无label -->
用户名:<input type="text" name="username">

法则2:提供清晰的标签

<!-- ✅ 推荐:清晰的标签 -->
<label for="phone">手机号码</label>
<input type="tel" id="phone" name="phone" placeholder="请输入11位手机号">

<!-- ❌ 不推荐:模糊的标签 -->
<label for="phone">联系方式</label>
<input type="text" id="phone" name="phone">

法则3:使用合适的输入类型

<!-- ✅ 推荐:使用正确的类型 -->
<input type="email" name="email">
<input type="tel" name="phone">
<input type="number" name="age">

<!-- ❌ 不推荐:全部使用text -->
<input type="text" name="email">
<input type="text" name="phone">
<input type="text" name="age">

法则4:提供占位符和帮助文本

<!-- ✅ 推荐:提供占位符 -->
<input type="text" name="username" placeholder="6-20个字符">
<small class="help-text">用户名只能包含字母、数字和下划线</small>

<!-- ❌ 不推荐:无任何提示 -->
<input type="text" name="username">

法则5:验证用户输入

<!-- ✅ 推荐:添加验证 -->
<input type="email" name="email" required>
<input type="password" name="password" minlength="6" required>

<!-- ❌ 不推荐:无验证 -->
<input type="text" name="email">
<input type="text" name="password">

法则6:合理分组

<!-- ✅ 推荐:使用fieldset分组 -->
<fieldset>
    <legend>个人信息</legend>
    <input type="text" name="name">
    <input type="number" name="age">
</fieldset>

<!-- ❌ 不推荐:无分组 -->
<input type="text" name="name">
<input type="number" name="age">

学习检验

知识点测试

问题1:以下哪个属性用于指定表单提交的HTTP方法?

A. action B. method C. type D. enctype

<details> <summary>点击查看答案</summary>

答案:B

东巴文解释:method属性用于指定表单提交的HTTP方法(GET或POST)。action指定提交地址,type是input的属性,enctype指定编码类型。

</details>

问题2:以下哪个input类型适合输入邮箱地址?

A. text B. email C. mail D. address

<details> <summary>点击查看答案</summary>

答案:B

东巴文解释:type="email"专门用于邮箱输入,会自动验证邮箱格式,移动端会显示邮箱键盘。HTML中没有mail和address类型。

</details>

实践任务

任务:创建一个完整的用户注册表单,包含以下功能:

  1. 用户名、邮箱、密码、确认密码输入
  2. 性别单选、爱好多选
  3. 城市下拉选择
  4. 个人简介文本域
  5. HTML5表单验证
  6. 美观的CSS样式
<details> <summary>点击查看参考答案</summary>
<!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>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        
        .container {
            background: white;
            padding: 40px;
            border-radius: 10px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.2);
            width: 100%;
            max-width: 500px;
        }
        
        h1 {
            text-align: center;
            color: #333;
            margin-bottom: 30px;
            font-size: 28px;
        }
        
        .form-group {
            margin-bottom: 20px;
        }
        
        label {
            display: block;
            margin-bottom: 8px;
            color: #555;
            font-weight: 500;
        }
        
        input[type="text"],
        input[type="email"],
        input[type="password"],
        input[type="tel"],
        select,
        textarea {
            width: 100%;
            padding: 12px;
            border: 2px solid #e0e0e0;
            border-radius: 6px;
            font-size: 14px;
            transition: border-color 0.3s, box-shadow 0.3s;
        }
        
        input:focus,
        select:focus,
        textarea:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
        
        input:invalid:not(:placeholder-shown) {
            border-color: #f44336;
        }
        
        input:valid:not(:placeholder-shown) {
            border-color: #4CAF50;
        }
        
        .radio-group,
        .checkbox-group {
            display: flex;
            gap: 20px;
            margin-top: 8px;
        }
        
        .radio-group label,
        .checkbox-group label {
            display: flex;
            align-items: center;
            gap: 5px;
            font-weight: normal;
            cursor: pointer;
        }
        
        input[type="radio"],
        input[type="checkbox"] {
            width: 18px;
            height: 18px;
            cursor: pointer;
        }
        
        textarea {
            resize: vertical;
            min-height: 100px;
        }
        
        .help-text {
            display: block;
            margin-top: 5px;
            font-size: 12px;
            color: #888;
        }
        
        button {
            width: 100%;
            padding: 14px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 6px;
            font-size: 16px;
            font-weight: bold;
            cursor: pointer;
            transition: transform 0.2s, box-shadow 0.2s;
        }
        
        button:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 20px rgba(102, 126, 234, 0.4);
        }
        
        button:active {
            transform: translateY(0);
        }
        
        .footer {
            text-align: center;
            margin-top: 20px;
            color: #888;
            font-size: 14px;
        }
        
        .footer a {
            color: #667eea;
            text-decoration: none;
        }
        
        .footer a:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>东巴文用户注册</h1>
        
        <form action="/register" method="post" novalidate>
            <div class="form-group">
                <label for="username">用户名 *</label>
                <input type="text" 
                       id="username" 
                       name="username" 
                       required
                       minlength="3"
                       maxlength="20"
                       pattern="[a-zA-Z0-9_]+"
                       placeholder="请输入用户名(3-20个字符)">
                <span class="help-text">只能包含字母、数字和下划线</span>
            </div>
            
            <div class="form-group">
                <label for="email">邮箱 *</label>
                <input type="email" 
                       id="email" 
                       name="email" 
                       required
                       placeholder="请输入邮箱地址">
            </div>
            
            <div class="form-group">
                <label for="password">密码 *</label>
                <input type="password" 
                       id="password" 
                       name="password" 
                       required
                       minlength="6"
                       maxlength="20"
                       placeholder="请输入密码(6-20个字符)">
                <span class="help-text">至少6个字符,建议包含字母和数字</span>
            </div>
            
            <div class="form-group">
                <label for="confirm-password">确认密码 *</label>
                <input type="password" 
                       id="confirm-password" 
                       name="confirm-password" 
                       required
                       placeholder="请再次输入密码">
            </div>
            
            <div class="form-group">
                <label>性别</label>
                <div class="radio-group">
                    <label>
                        <input type="radio" name="gender" value="male"> 男
                    </label>
                    <label>
                        <input type="radio" name="gender" value="female"> 女
                    </label>
                    <label>
                        <input type="radio" name="gender" value="other"> 其他
                    </label>
                </div>
            </div>
            
            <div class="form-group">
                <label>爱好</label>
                <div class="checkbox-group">
                    <label>
                        <input type="checkbox" name="hobby" value="reading"> 阅读
                    </label>
                    <label>
                        <input type="checkbox" name="hobby" value="music"> 音乐
                    </label>
                    <label>
                        <input type="checkbox" name="hobby" value="sports"> 运动
                    </label>
                    <label>
                        <input type="checkbox" name="hobby" value="travel"> 旅行
                    </label>
                </div>
            </div>
            
            <div class="form-group">
                <label for="city">所在城市</label>
                <select id="city" name="city">
                    <option value="">请选择城市</option>
                    <optgroup label="直辖市">
                        <option value="beijing">北京</option>
                        <option value="shanghai">上海</option>
                        <option value="tianjin">天津</option>
                        <option value="chongqing">重庆</option>
                    </optgroup>
                    <optgroup label="省会城市">
                        <option value="guangzhou">广州</option>
                        <option value="shenzhen">深圳</option>
                        <option value="hangzhou">杭州</option>
                        <option value="chengdu">成都</option>
                    </optgroup>
                </select>
            </div>
            
            <div class="form-group">
                <label for="bio">个人简介</label>
                <textarea id="bio" 
                          name="bio" 
                          rows="4"
                          maxlength="200"
                          placeholder="请简单介绍一下自己(最多200字)"></textarea>
            </div>
            
            <button type="submit">立即注册</button>
            
            <div class="footer">
                已有账号?<a href="/login">立即登录</a>
            </div>
        </form>
    </div>
    
    <script>
        // 密码确认验证
        const form = document.querySelector('form');
        const password = document.getElementById('password');
        const confirmPassword = document.getElementById('confirm-password');
        
        confirmPassword.addEventListener('input', function() {
            if (this.value !== password.value) {
                this.setCustomValidity('两次输入的密码不一致');
            } else {
                this.setCustomValidity('');
            }
        });
        
        form.addEventListener('submit', function(e) {
            if (!form.checkValidity()) {
                e.preventDefault();
                alert('请正确填写所有必填项!');
            }
        });
    </script>
</body>
</html>
</details>

东巴文(db-w.cn) - 让编程学习更有趣、更高效!