HTML5 表单元素学习笔记

1. 表单基础

HTML5 中的表单元素用于收集用户输入的数据。在表单中,使用 <form> 元素包含表单内的所有元素。

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

表单必须指定 actionmethod 属性,其中 action 属性指定提交表单数据到哪个 URL,而 method 属性指定使用哪种 HTTP 方法提交表单数据,可以为 “get” 或 “post”。

2. 常用表单元素

2.1 文本输入

使用 <input> 元素创建文本输入框。它有多个类型可以使用,最常见的是 text 类型:

htmlCopy Code
<label for="username">用户名:</label> <input type="text" id="username" name="username">

2.2 密码输入

密码输入框会将用户的输入隐藏起来,使用时需要设置 type="password"

htmlCopy Code
<label for="password">密码:</label> <input type="password" id="password" name="password">

2.3 单选按钮和复选框

单选按钮使用 <input> 元素创建,同时使用 type="radio" 属性进行标识。不同的单选按钮需要使用相同的 name 属性。

htmlCopy Code
<label></label> <input type="radio" name="gender" value="male"> <label></label> <input type="radio" name="gender" value="female">

复选框使用 <input> 元素创建,同时使用 type="checkbox" 属性进行标识。每个复选框可以拥有一个独立的 name 属性。

htmlCopy Code
<label>蓝色</label> <input type="checkbox" name="color" value="blue"> <label>红色</label> <input type="checkbox" name="color" value="red"> <label>黄色</label> <input type="checkbox" name="color" value="yellow">

2.4 下拉列表

下拉列表使用 <select> 元素创建,其中 <option> 元素用于定义每个选项。下列代码创建了一个包含三个选项的下拉列表:

htmlCopy Code
<label for="fruit">选择你喜欢的水果:</label> <select id="fruit" name="fruit"> <option value="apple">苹果</option> <option value="banana">香蕉</option> <option value="orange">橙子</option> </select>

2.5 文本区域

文本区域使用 <textarea> 元素创建,可以让用户键入多行文本:

htmlCopy Code
<label for="message">留言:</label> <textarea id="message" name="message"></textarea>

3. 实例演示

以下是一个简单的表单,包含一个文本输入框、一个密码输入框、两个单选按钮、三个复选框和一个下拉列表:

htmlCopy Code
<form action="/submit-form" method="post"> <label for="username">用户名:</label> <input type="text" id="username" name="username"> <label for="password">密码:</label> <input type="password" id="password" name="password"> <p>性别:</p> <label></label> <input type="radio" name="gender" value="male"> <label></label> <input type="radio" name="gender" value="female"> <p>喜欢的颜色:</p> <label>蓝色</label> <input type="checkbox" name="color" value="blue"> <label>红色</label> <input type="checkbox" name="color" value="red"> <label>黄色</label> <input type="checkbox" name="color" value="yellow"> <p>选择你喜欢的水果:</p> <select id="fruit" name="fruit"> <option value="apple">苹果</option> <option value="banana">香蕉</option> <option value="orange">橙子</option> </select> <p>留言:</p> <textarea id="message" name="message"></textarea> <button type="submit">提交</button> </form>

以上就是 HTML5 表单元素的学习笔记和一个实例演示。