js实现单选效果
使用HTML和JavaScript实现单选效果
通过HTML的<input type="radio">元素结合JavaScript可以实现单选效果。以下是具体实现方法:
<input type="radio" name="option" value="1" id="option1">
<label for="option1">选项1</label>
<input type="radio" name="option" value="2" id="option2">
<label for="option2">选项2</label>
<input type="radio" name="option" value="3" id="option3">
<label for="option3">选项3</label>
// 获取所有单选按钮
const radioButtons = document.querySelectorAll('input[name="option"]');
// 为每个单选按钮添加事件监听器
radioButtons.forEach(radio => {
radio.addEventListener('change', function() {
if (this.checked) {
console.log('选中值:', this.value);
}
});
});
使用CSS自定义单选按钮样式
如果需要自定义单选按钮的样式,可以隐藏原生单选按钮并使用CSS伪元素创建自定义样式:
input[type="radio"] {
display: none;
}
input[type="radio"] + label:before {
content: "";
display: inline-block;
width: 16px;
height: 16px;
margin-right: 8px;
border: 2px solid #ccc;
border-radius: 50%;
vertical-align: middle;
}
input[type="radio"]:checked + label:before {
background-color: #2196F3;
border-color: #2196F3;
}
使用JavaScript动态控制单选按钮
可以通过JavaScript动态设置单选按钮的选中状态:
// 设置第二个选项为选中状态
document.getElementById('option2').checked = true;
// 获取当前选中的值
const selectedValue = document.querySelector('input[name="option"]:checked').value;
console.log('当前选中:', selectedValue);
使用事件委托优化性能
对于大量单选按钮,可以使用事件委托提高性能:
document.addEventListener('change', function(e) {
if (e.target.matches('input[type="radio"]')) {
console.log('选中:', e.target.value);
}
});
完整示例
以下是一个完整的HTML示例,包含单选按钮组和获取选中值的按钮:
<!DOCTYPE html>
<html>
<head>
<style>
.radio-group {
margin: 20px 0;
}
input[type="radio"] {
margin-right: 10px;
}
button {
margin-top: 10px;
padding: 5px 15px;
}
</style>
</head>
<body>
<div class="radio-group">
<input type="radio" name="color" value="red" id="red">
<label for="red">红色</label><br>
<input type="radio" name="color" value="green" id="green">
<label for="green">绿色</label><br>
<input type="radio" name="color" value="blue" id="blue">
<label for="blue">蓝色</label>
</div>
<button id="getValue">获取选中值</button>
<script>
document.getElementById('getValue').addEventListener('click', function() {
const selected = document.querySelector('input[name="color"]:checked');
if (selected) {
alert('当前选中: ' + selected.value);
} else {
alert('请先选择一个选项');
}
});
</script>
</body>
</html>






