您现在的位置是:网站首页 > <input>-输入控件文章详情
<input>-输入控件
陈川
【
HTML
】
7719人已围观
3260字
<input>
是 HTML 中最基础且功能丰富的表单控件之一,用于接收用户输入。它通过 type
属性支持多种输入类型,包括文本、密码、复选框、单选按钮等。以下内容将详细解析其用法、属性和实际应用场景。
<input>
的基本语法
<input>
是一个空元素(没有闭合标签),基本语法如下:
<input type="text" name="username" id="username">
关键属性:
type
:定义输入类型(如text
、password
、email
等)。name
:标识表单数据提交时的字段名。id
:用于关联<label>
或 JavaScript 操作。
<input>
的常见类型
文本输入(text)
默认类型,用于单行文本输入:
<input type="text" name="search" placeholder="输入关键词">
密码输入(password)
隐藏输入内容,显示为圆点或星号:
<input type="password" name="pwd" minlength="8" required>
复选框(checkbox)
允许用户多选:
<input type="checkbox" name="hobby" value="reading" id="hobby1">
<label for="hobby1">阅读</label>
<input type="checkbox" name="hobby" value="sports" id="hobby2">
<label for="hobby2">运动</label>
单选按钮(radio)
限制用户只能选择一个选项:
<input type="radio" name="gender" value="male" id="male">
<label for="male">男</label>
<input type="radio" name="gender" value="female" id="female">
<label for="female">女</label>
文件上传(file)
允许用户选择本地文件:
<input type="file" name="avatar" accept="image/*">
日期和时间选择器
现代浏览器支持的日期时间输入:
<input type="date" name="birthday">
<input type="time" name="meeting-time">
<input type="datetime-local" name="event-time">
高级属性和功能
输入验证
通过 HTML5 属性实现客户端验证:
<input type="email" name="email" required placeholder="输入有效邮箱">
<input type="number" name="age" min="18" max="100">
<input type="url" name="website" pattern="https?://.+">
数据列表(datalist)
提供输入建议:
<input list="browsers" name="browser">
<datalist id="browsers">
<option value="Chrome">
<option value="Firefox">
<option value="Safari">
</datalist>
隐藏字段(hidden)
存储不显示但需要提交的数据:
<input type="hidden" name="user_id" value="12345">
样式和交互增强
使用 CSS 定制样式
通过伪类选择器美化状态:
input[type="text"] {
padding: 8px;
border: 2px solid #ccc;
border-radius: 4px;
}
input:focus {
border-color: #4CAF50;
}
JavaScript 动态控制
实时监听输入变化:
<input type="text" id="live-search" placeholder="输入搜索内容">
<script>
document.getElementById('live-search').addEventListener('input', function(e) {
console.log('当前输入:', e.target.value);
});
</script>
实际应用示例
登录表单
结合多种输入类型:
<form action="/login" method="post">
<label for="email">邮箱:</label>
<input type="email" id="email" name="email" required>
<label for="password">密码:</label>
<input type="password" id="password" name="password" minlength="6" required>
<label>
<input type="checkbox" name="remember"> 记住我
</label>
<button type="submit">登录</button>
</form>
动态表单字段
通过 JavaScript 添加新输入框:
<div id="phone-list">
<input type="tel" name="phones[]" placeholder="电话号码">
</div>
<button onclick="addPhoneField()">添加号码</button>
<script>
function addPhoneField() {
const div = document.getElementById('phone-list');
const newInput = document.createElement('input');
newInput.type = 'tel';
newInput.name = 'phones[]';
newInput.placeholder = '电话号码';
div.appendChild(newInput);
}
</script>
兼容性和注意事项
- 旧版浏览器可能不支持某些
type
(如date
),需使用 Polyfill 或备用方案。 - 表单提交时,只有包含
name
属性的输入字段会被包含在请求中。 - 移动设备上不同的输入类型会触发优化的虚拟键盘(如
type="email"
显示 @ 符号)。
上一篇: <form>-表单容器
下一篇: <textarea>-多行文本输入