在前端开发中,表单是收集用户信息的重要工具,而input
标签则是表单中最常用的元素之一。input
标签有多种类型,其中单选框(radio
)允许用户从一组选项中选择一个。本文将详细介绍如何在 HTML5 中使用input
标签实现单选框,并给出相关的演示代码。
单选框的主要特点是在一组选项中,用户只能选择其中一个。这是通过为同一组单选框设置相同的name
属性来实现的。当用户选择一个单选框时,其他具有相同name
属性的单选框会自动取消选中状态。
下面是一个简单的单选框示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>单选框示例</title>
</head>
<body>
<form>
<label for="option1">选项 1</label>
<input type="radio" id="option1" name="choice" value="option1">
<br>
<label for="option2">选项 2</label>
<input type="radio" id="option2" name="choice" value="option2">
<br>
<input type="submit" value="提交">
</form>
</body>
</html>
input
标签:type="radio"
指定该input
元素为单选框。name
属性:同一组单选框必须具有相同的name
属性,这里都设置为choice
,表示它们是一组选项。id
属性:为每个单选框设置唯一的id
,方便与对应的label
标签关联。value
属性:每个单选框都有一个value
属性,当表单提交时,该值会被发送到服务器,用于标识用户选择的选项。label
标签:通过for
属性与单选框的id
关联,点击label
文本时,对应的单选框会被选中,提高用户体验。有时候,我们希望在页面加载时就预选中某个选项,可以使用checked
属性。以下是示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>预选中单选框示例</title>
</head>
<body>
<form>
<label for="option1">选项 1</label>
<input type="radio" id="option1" name="choice" value="option1">
<br>
<label for="option2">选项 2</label>
<input type="radio" id="option2" name="choice" value="option2" checked>
<br>
<input type="submit" value="提交">
</form>
</body>
</html>
在上述代码中,checked
属性被添加到第二个单选框上,因此页面加载时,第二个选项会被预选中。
属性 | 描述 |
---|---|
type="radio" |
指定input 元素为单选框 |
name |
同一组单选框必须具有相同的name 属性,用于区分不同的选项组 |
id |
为每个单选框设置唯一的id ,方便与label 标签关联 |
value |
单选框的值,表单提交时会发送到服务器 |
checked |
可选属性,用于预选中某个选项 |
通过以上的介绍和示例代码,我们可以看到在 HTML5 中使用input
标签实现单选框非常简单。合理运用name
、id
、value
和checked
等属性,可以满足各种单选框的使用场景。希望本文对你理解和使用 HTML5 中的单选框有所帮助。