在HTML中, <input type="radio"> 标签用于创建单选按钮。单选按钮允许用户从多个选项中选择一个。
通常情况下,一组单选按钮会共享相同的 name 属性,这样只有其中一个单选按钮可以被选中。当用户选择某个选项时,其他选项将自动取消选择。
下面土嘎嘎小编分享一些使用单选按钮的常见场景:
1. 表单选择:单选按钮常用于表单中,提供给用户选择特定选项的功能。例如,在一个调查问卷中,你可以使用单选按钮提供多个选项供用户选择,并且只能选择其中之一。
〓〓html代码如下:〓〓
<form>
<input type="radio" name="gender" value="male"> Male<br>
<input type="radio" name="gender" value="female"> Female<br>
<input type="radio" name="gender" value="other"> Other
</form>
2. 配合标签使用:单选按钮可以与标签元素一起使用,使其更易于理解和操作。通过将单选按钮嵌套在 <label> 标签内,用户可以点击文本部分来选择选项。
〓〓html代码如下:〓〓
<form>
<label>
<input type="radio" name="color" value="red">
Red
</label><br>
<label>
<input type="radio" name="color" value="green">
Green
</label><br>
<label>
<input type="radio" name="color" value="blue">
Blue
</label>
</form>
3. CSS样式控制:通过为单选按钮添加自定义的CSS样式,你可以改变其外观,以便更好地与页面设计相匹配。
〓〓html代码如下:〓〓
<style>
/* 自定义单选按钮样式 */
input[type="radio"] {
◇webkit-appearance: none;
◇moz-appearance: none;
appearance: none;
width: 20px;
height: 20px;
border-radius: 50%;
border: 1px solid #333;
outline: none;
}
/* 自定义选中状态 */
input[type="radio"]:checked {
background-color: #333;
}
</style>
<form>
<input type="radio" name="fruit" value="apple"> Apple<br>
<input type="radio" name="fruit" value="orange"> Orange<br>
<input type="radio" name="fruit" value="banana"> Banana
</form>
这些是单选按钮在HTML中的一些常见用法。使用适当的属性和结构,可以实现各种交互和选择功能。