Skip to content

HTML 输入类型

<input> 元素功能极其丰富。它的行为和外观会根据其 type 属性发生显著变化。本章将探讨最常见和有用的输入类型(input types)。

现代 Web 表单高度依赖使用正确的输入类型来提供更好的用户体验(user experience)、可访问性(accessibility)和内置的浏览器验证(validation)。

<input type="text"> 定义一个单行文本输入字段。如果没有指定 type,这是默认类型。

最佳实践:始终将你的输入框与 <label> 元素配对使用,以提高可访问性。标签的 for 属性应与输入框的 id 匹配。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Text Input Example</title>
<style>
label {
display: block;
margin-bottom: 5px;
}
input[type="text"] {
margin-bottom: 10px;
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
}
</style>
</head>
<body>
<form>
<label for="fname">First name:</label>
<input type="text" id="fname" name="firstname">
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lastname">
</form>
</body>
</html>

常用属性:placeholder、required、minlength、maxlength、pattern(用于使用正则表达式进行特定格式验证)。

<input type="password"> 定义一个密码字段。输入的字符会被遮蔽(显示为星号或圆点)以保证安全。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Password Input Example</title>
<style> /* Basic styling */
label { display: block; margin-bottom: 5px; }
input { margin-bottom: 10px; padding: 8px; border: 1px solid #ccc; border-radius: 4px; }
</style>
</head>
<body>
<form>
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<label for="pwd">Password:</label>
<input type="password" id="pwd" name="password" required minlength="8">
</form>
</body>
</html>

注意:虽然输入内容在视觉上被遮蔽,但数据除非通过 HTTPS 提交,否则会以明文形式发送。始终使用 HTTPS 来处理敏感数据。

<input type="submit"> 定义一个按钮,用于将表单数据提交到服务器端处理程序。

表单处理程序的 URL 在 <form> 元素的 action 属性中指定,而 HTTP 方法(通常是 GET 或 POST)在 method 属性中指定。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Submit Button Example</title>
<style> /* Basic styling */
label { display: block; margin-bottom: 5px; }
input[type="text"] { margin-bottom: 10px; padding: 8px; border: 1px solid #ccc; border-radius: 4px; }
input[type="submit"] { padding: 10px 15px; background-color: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; }
input[type="submit"]:hover { background-color: #0056b3; }
</style>
</head>
<body>
<form action="/process-form" method="post">
<label for="email">Email:</label>
<input type="email" id="email" name="user_email" required>
<input type="submit" value="Sign Up">
</form>
</body>
</html>

value 属性设置按钮上显示的文本。如果省略,浏览器会显示一个默认值,例如“Submit”。考虑使用 <button type="submit"> 元素来获得更大的样式灵活性。

<input type="radio"> 定义一个单选按钮(radio button)。单选按钮允许用户从一组选项中只选择一个。

同一组中的所有单选按钮必须共享相同的 name 属性。使用 checked 属性可以预先选择一个选项。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Radio Button Example</title>
<style> /* Basic styling */
fieldset { border: 1px solid #ccc; padding: 15px; margin-bottom: 10px; }
legend { font-weight: bold; }
label { margin-right: 15px; }
</style>
</head>
<body>
<form>
<fieldset>
<legend>Choose your preferred contact method:</legend>
<input type="radio" id="contact_email" name="contact_method" value="email" checked>
<label for="contact_email">Email</label>
<input type="radio" id="contact_phone" name="contact_method" value="phone">
<label for="contact_phone">Phone</label>
<input type="radio" id="contact_mail" name="contact_method" value="mail">
<label for="contact_mail">Mail</label>
</fieldset>
</form>
</body>
</html>

使用 <fieldset> 和 <legend> 可以改善相关控件组的结构和可访问性。

<input type="checkbox"> 定义一个复选框(checkbox)。复选框允许用户从列表中选择零个或多个选项。

每个复选框通常有一个唯一的 value。共享相同 name 的复选框可以在服务器上作为一组进行处理。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Checkbox Example</title>
<style> /* Basic styling */
fieldset { border: 1px solid #ccc; padding: 15px; margin-bottom: 10px; }
legend { font-weight: bold; }
label { display: block; margin-bottom: 5px; }
</style>
</head>
<body>
<form>
<fieldset>
<legend>Select your interests:</legend>
<input type="checkbox" id="interest_music" name="interests[]" value="music">
<label for="interest_music">Music</label>
<input type="checkbox" id="interest_sports" name="interests[]" value="sports" checked>
<label for="interest_sports">Sports</label>
<input type="checkbox" id="interest_tech" name="interests[]" value="technology">
<label for="interest_tech">Technology</label>
</fieldset>
</form>
</body>
</html>

注意:使用 name="interests[]" 是一种常见的约定(尤其是在 PHP 中),它表明可能会提交多个“interests”的值。

<input type="button"> 定义一个通用按钮。它没有默认行为(不像 type="submit" 或 type="reset")。

这些按钮通常与 JavaScript 一起使用,以触发自定义操作。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Button Input Example</title>
<style> /* Basic styling */
input[type="button"] { padding: 10px 15px; background-color: #6c757d; color: white; border: none; border-radius: 4px; cursor: pointer; }
input[type="button"]:hover { background-color: #5a6268; }
</style>
</head>
<body>
<input type="button" value="Show Message" onclick="alert('Hello World!')">
<script>
// 现代方法:通过 JavaScript 附加事件监听器
// const myButton = document.getElementById('myCustomButton');
// myButton.addEventListener('click', () => {
// alert('Button clicked!');
// });
</script>
<!-- <input type="button" id="myCustomButton" value="Click Me (JS)"> -->
</body>
</html>

虽然 onclick 可以工作,但通常推荐使用 JavaScript 的 addEventListener 方法来附加事件监听器,以实现更好的关注点分离(separation of concerns)。

HTML5 引入了几种新的输入类型,它们改善了用户体验并支持更好的验证:

  • color
  • date
  • datetime-local
  • email
  • month
  • number
  • range
  • search
  • tel
  • time
  • url
  • week
  • file

浏览器为这些类型提供了专门的 UI 控件(如日期选择器 date pickers、颜色选择器 color pickers、滑块 sliders)和验证功能。如果浏览器不支持特定类型,它通常会回退到显示为 type="text"。

<input type="number"> 用于应包含数值的字段。浏览器可能会显示微调按钮(spinner controls)。

min、max 和 step 等属性允许设置可接受的范围和增量。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Number Input Example</title>
<style> /* Basic styling */
label { display: block; margin-bottom: 5px; }
input { margin-bottom: 10px; padding: 8px; border: 1px solid #ccc; border-radius: 4px; }
</style>
</head>
<body>
<form>
<label for="quantity">Quantity (between 1 and 10):</label>
<input type="number" id="quantity" name="quantity" min="1" max="10" value="1">
<label for="rating">Rating (0 to 5, steps of 0.5):</label>
<input type="number" id="rating" name="rating" min="0" max="5" step="0.5">
</form>
</body>
</html>

<input type="date"> 提供了一个用于选择日期(年、月、日)的控件。大多数浏览器会显示日期选择器(date picker)。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Date Input Example</title>
<style> /* Basic styling */
label { display: block; margin-bottom: 5px; }
input { margin-bottom: 10px; padding: 8px; border: 1px solid #ccc; border-radius: 4px; }
</style>
</head>
<body>
<form>
<label for="birthdate">Birth Date:</label>
<input type="date" id="birthdate" name="birthdate">
<label for="startdate">Project Start (after 2024-01-01):</label>
<input type="date" id="startdate" name="startdate" min="2024-01-02">
<label for="enddate">Project End (before 2025-01-01):</label>
<input type="date" id="enddate" name="enddate" max="2024-12-31">
</form>
</body>
</html>

显示的日期格式取决于浏览器和操作系统区域设置(OS locale),但提交的值是标准化的(YYYY-MM-DD)。

<input type="color"> 提供一个用于选择颜色的 UI(用户界面)。浏览器通常会显示一个颜色选择器(color picker)。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Color Input Example</title>
<style> /* Basic styling */
label { display: block; margin-bottom: 5px; }
input[type="color"] { vertical-align: middle; width: 50px; height: 30px; padding: 0; border: none; }
</style>
</head>
<body>
<form>
<label for="favcolor">Select your favorite color:</label>
<input type="color" id="favcolor" name="favcolor" value="#ff0000"> <!-- Default to red -->
</form>
</body>
</html>

提交的值是十六进制颜色代码(例如,#RRGGBB)。

<input type="range"> 定义一个用于输入数值的控件,该数值的精确值不那么关键。浏览器通常将其显示为滑块(slider)。

使用 min、max、step 和 value 属性来配置滑块。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Range Input Example</title>
<style> /* Basic styling */
label { display: block; margin-bottom: 5px; }
input[type="range"] { width: 200px; }
</style>
</head>
<body>
<form oninput="output.value=volume.value">
<label for="volume">Volume:</label>
<input type="range" id="volume" name="volume" min="0" max="100" value="50" step="1">
<output name="output" for="volume">50</output>
</form>
</body>
</html>

考虑添加一个 <output> 元素或使用 JavaScript 来显示当前值,因为滑块并不总是很精确。

<input type="email"> 用于应包含电子邮件地址的字段。

浏览器在提交时会提供电子邮件格式的基本验证。移动设备通常会显示专用的键盘。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Email Input Example</title>
<style> /* Basic styling */
label { display: block; margin-bottom: 5px; }
input { margin-bottom: 10px; padding: 8px; border: 1px solid #ccc; border-radius: 4px; width: 250px; }
</style>
</head>
<body>
<form>
<label for="user_email">Enter your email:</label>
<input type="email" id="user_email" name="user_email" placeholder="you@example.com" required>
</form>
</body>
</html>

multiple 属性允许输入一个逗号分隔的电子邮件地址列表。

<input type="tel"> 用于应包含电话号码的字段。

与 email 或 url 不同,tel 不强制执行特定格式,因为全球电话号码格式差异很大。它的主要好处是在移动设备上触发优化过的数字键盘。

使用带有正则表达式的 pattern 属性进行特定格式验证。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Telephone Input Example</title>
<style> /* Basic styling */
label { display: block; margin-bottom: 5px; }
input { margin-bottom: 10px; padding: 8px; border: 1px solid #ccc; border-radius: 4px; }
</style>
</head>
<body>
<form>
<label for="phone">Phone Number (Format: 123-456-7890):</label>
<input type="tel" id="phone" name="phone"
pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"
placeholder="123-456-7890" required>
</form>
</body>
</html>

<input type="url"> 用于应包含 URL 地址的字段。

浏览器对 URL 格式执行基本验证(要求类似 scheme://... 的格式)。移动设备可能会提供 URL 专用的键盘快捷键。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>URL Input Example</title>
<style> /* Basic styling */
label { display: block; margin-bottom: 5px; }
input { margin-bottom: 10px; padding: 8px; border: 1px solid #ccc; border-radius: 4px; width: 300px; }
</style>
</head>
<body>
<form>
<label for="homepage">Add your homepage URL:</label>
<input type="url" id="homepage" name="homepage"
placeholder="https://example.com" required>
</form>
</body>
</html>

与 date 类似,HTML5 提供了更精细的时间输入类型:

  • datetime-local:选择日期和时间(无时区)。它取代了已废弃的 datetime 类型。
  • month:选择月份和年份。
  • week:选择周和年份。
  • time:选择时间(时、分、秒;无时区)。

这些类型通常在支持的浏览器中呈现为专用的控件。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Time Inputs Example</title>
<style> /* Basic styling */
label { display: block; margin-bottom: 5px; }
input { margin-bottom: 10px; padding: 8px; border: 1px solid #ccc; border-radius: 4px; }
</style>
</head>
<body>
<form>
<label for="meeting-time">Meeting Time:</label>
<input type="datetime-local" id="meeting-time" name="meeting-time">
<label for="start-month">Project Start Month:</label>
<input type="month" id="start-month" name="start-month">
<label for="delivery-week">Delivery Week:</label>
<input type="week" id="delivery-week" name="delivery-week">
<label for="alarm-time">Alarm Time:</label>
<input type="time" id="alarm-time" name="alarm-time">
</form>
</body>
</html>

<input type="search"> 用于搜索字段。功能上,它的行为类似于 type="text",但浏览器可能会以不同方式对其进行样式设置(例如,圆角)或添加清除按钮(clear button)。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Search Input Example</title>
<style> /* Basic styling */
label { display: block; margin-bottom: 5px; }
input { margin-bottom: 10px; padding: 8px; border: 1px solid #ccc; border-radius: 4px; }
</style>
</head>
<body>
<form>
<label for="site-search">Search this site:</label>
<input type="search" id="site-search" name="query">
<button type="submit">Search</button>
</form>
</body>
</html>

<input type="file"> 允许用户从其设备存储中选择一个或多个文件。浏览器会渲染一个按钮和文本,指示选择状态。

使用 accept 属性来建议文件类型(例如,accept="image/*"、accept=".pdf,.docx")。multiple 属性允许选择多个文件。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>File Input Example</title>
<style> /* Basic styling */
label { display: block; margin-bottom: 5px; }
input { margin-bottom: 10px; }
</style>
</head>
<body>
<!-- Remember to set enctype="multipart/form-data" on the form -->
<form action="/upload" method="post" enctype="multipart/form-data">
<label for="avatar">Upload Profile Picture (JPEG/PNG):</label>
<input type="file" id="avatar" name="avatar" accept="image/jpeg, image/png">
<label for="docs">Upload Documents (PDF/DOCX):</label>
<input type="file" id="docs" name="documents[]" accept=".pdf,.docx" multiple>
<button type="submit">Upload</button>
</form>
</body>
</html>

重要提示:为了使文件上传工作,表单的 method 必须是 post,并且 enctype 属性必须设置为 multipart/form-data。

HTML5 提供了用于客户端验证(client-side validation)的属性,通过在提交前捕获错误来改善用户体验:

属性描述
required指定提交前必须填写输入字段。
pattern指定输入值必须匹配的正则表达式。
min / max指定允许的最小值和最大值(用于 numeric、date、time、range 类型)。
step指定合法的数值间隔(用于 numeric、date、time、range 类型)。
minlength / maxlength指定最小和最大字符数(用于 text、email、search、password、tel、url)。
disabled指定输入字段应被禁用(不可编辑且不提交)。
readonly指定输入字段无法更改,但其值仍然会提交。
placeholder提供关于用户应输入内容的提示(在聚焦/输入时消失)。

尽管客户端验证很有帮助,但为了安全起见,始终应该通过服务器端验证(server-side validation)进行补充。