js 实现 radio
使用原生JavaScript实现Radio按钮组
创建HTML结构
<div class="radio-group">
<label>
<input type="radio" name="gender" value="male"> Male
</label>
<label>
<input type="radio" name="gender" value="female"> Female
</label>
</div>
获取选中值
const radioButtons = document.querySelectorAll('input[name="gender"]');
let selectedValue;
for (const radioButton of radioButtons) {
if (radioButton.checked) {
selectedValue = radioButton.value;
break;
}
}
console.log(selectedValue);
添加事件监听

radioButtons.forEach(radio => {
radio.addEventListener('change', function() {
if (this.checked) {
console.log(`Selected: ${this.value}`);
}
});
});
动态生成Radio按钮组
创建动态Radio按钮
const options = ['Red', 'Green', 'Blue'];
const container = document.getElementById('color-options');
options.forEach(option => {
const label = document.createElement('label');
const radio = document.createElement('input');
radio.type = 'radio';
radio.name = 'color';
radio.value = option.toLowerCase();
label.appendChild(radio);
label.appendChild(document.createTextNode(option));
container.appendChild(label);
});
自定义Radio按钮样式
CSS样式

.custom-radio input[type="radio"] {
opacity: 0;
position: absolute;
}
.custom-radio label {
position: relative;
padding-left: 25px;
cursor: pointer;
}
.custom-radio label:before {
content: '';
position: absolute;
left: 0;
top: 0;
width: 18px;
height: 18px;
border: 2px solid #ddd;
border-radius: 50%;
}
.custom-radio input[type="radio"]:checked + label:after {
content: '';
position: absolute;
left: 5px;
top: 5px;
width: 12px;
height: 12px;
background: #2196F3;
border-radius: 50%;
}
使用Radio按钮控制显示内容
HTML结构
<input type="radio" name="display" value="tab1" checked> Tab 1
<input type="radio" name="display" value="tab2"> Tab 2
<div id="tab1-content">Content for Tab 1</div>
<div id="tab2-content" style="display:none">Content for Tab 2</div>
JavaScript控制
document.querySelectorAll('input[name="display"]').forEach(radio => {
radio.addEventListener('change', function() {
document.getElementById('tab1-content').style.display =
this.value === 'tab1' ? 'block' : 'none';
document.getElementById('tab2-content').style.display =
this.value === 'tab2' ? 'block' : 'none';
});
});






