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>
<label>
<input type="radio" name="gender" value="other"> Other
</label>
</div>
添加JavaScript交互逻辑
// 获取所有radio按钮
const radioButtons = document.querySelectorAll('input[name="gender"]');
// 为每个radio按钮添加事件监听
radioButtons.forEach(radio => {
radio.addEventListener('change', function() {
if(this.checked) {
console.log('Selected value:', this.value);
}
});
});
动态创建Radio按钮组
通过JavaScript动态生成

const options = ['Red', 'Green', 'Blue'];
const container = document.getElementById('radio-container');
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值
使用querySelector查找被选中的项
function getSelectedRadioValue(name) {
const selected = document.querySelector(`input[name="${name}"]:checked`);
return selected ? selected.value : null;
}
// 使用示例
const selectedGender = getSelectedRadioValue('gender');
设置默认选中状态
通过设置checked属性

// 设置第一个radio为默认选中
document.querySelector('input[name="gender"]').checked = true;
// 或者通过值来设置
function setRadioValue(name, value) {
const radio = document.querySelector(`input[name="${name}"][value="${value}"]`);
if(radio) radio.checked = true;
}
自定义Radio按钮样式
CSS样式示例
.radio-custom {
opacity: 0;
position: absolute;
}
.radio-custom + label {
position: relative;
padding-left: 25px;
cursor: pointer;
}
.radio-custom + label:before {
content: '';
position: absolute;
left: 0;
top: 0;
width: 18px;
height: 18px;
border: 2px solid #ddd;
border-radius: 50%;
}
.radio-custom:checked + label:after {
content: '';
position: absolute;
left: 5px;
top: 5px;
width: 12px;
height: 12px;
background: #2196F3;
border-radius: 50%;
}
HTML结构
<input type="radio" id="radio1" name="custom-radio" class="radio-custom">
<label for="radio1">Option 1</label>
<input type="radio" id="radio2" name="custom-radio" class="radio-custom">
<label for="radio2">Option 2</label>






