生成一个自定义的单选框
时间: 2024-09-08 12:02:56 浏览: 94
在JavaScript中,创建一个自定义的单选框(Radio Button)通常使用HTML元素结合JavaScript来实现交互效果。以下是一个简单的示例,展示了如何创建一个带有点击事件监听的单选按钮:
```html
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.custom-radio {
display: inline-block;
position: relative;
width: 20px;
height: 20px;
margin-right: 5px;
cursor: pointer;
}
.custom-radio input[type="radio"] {
position: absolute;
opacity: 0;
z-index: -1;
}
.custom-radio::before {
content: "";
display: inline-block;
border: 1px solid #ccc;
background-color: #fff;
width: 18px;
height: 18px;
transition: all 0.2s ease;
}
.custom-radio:checked::before {
background-color: blue;
}
</style>
</head>
<body>
<label class="custom-radio" onclick="toggleOption(this)">
<input type="radio" name="myRadio" id="option1">
<span>Option 1</span>
</label>
<label class="custom-radio">
<input type="radio" name="myRadio" id="option2">
<span>Option 2</span>
</label>
<script>
function toggleOption(radioButton) {
const radios = document.getElementsByName('myRadio');
for (let i = 0; i < radios.length; i++) {
if (radios[i] !== radioButton && radios[i].checked) {
radios[i].checked = false;
radioButton.classList.remove('selected');
} else {
radioButton.classList.add('selected');
radioButton.checked = true;
break;
}
}
}
</script>
</body>
</html>
```
这个例子中,我们创建了两个样式化的`<label>`元素,每个标签内部包含一个`<input>`类型的单选按钮和文本描述。当用户点击`<label>`时,`toggleOption`函数会被调用,会检查同名的其他单选按钮是否已经选中,如果选中则取消选中并改变样式,否则只选中当前按钮。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://img-home.csdnimg.cn/images/20250102104920.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)