以下是关于全 JS 自定义单选框的相关内容:
基础概念: 自定义单选框是指通过 JavaScript 来完全掌控单选框的外观、行为和交互效果,不再依赖浏览器默认的单选框样式。
优势:
类型:
应用场景:
可能出现的问题及原因:
解决方法:
示例代码(纯 HTML、CSS、JavaScript 实现简单自定义单选框):
HTML:
<div class="custom-radio">
<input type="radio" id="option1" name="options" checked>
<label for="option1">选项 1</label>
</div>
<div class="custom-radio">
<input type="radio" id="option2" name="options">
<label for="option2">选项 2</label>
</div>
CSS:
.custom-radio input {
display: none;
}
.custom-radio label {
position: relative;
padding-left: 30px;
cursor: pointer;
}
.custom-radio label::before {
content: '';
position: absolute;
left: 0;
top: 50%;
transform: translateY(-50%);
width: 20px;
height: 20px;
border: 2px solid #ccc;
border-radius: 50%;
}
.custom-radio input:checked + label::after {
content: '';
position: absolute;
left: 6px;
top: 50%;
transform: translateY(-50%);
width: 10px;
height: 10px;
background-color: #007bff;
border-radius: 50%;
}
JavaScript:
const radios = document.querySelectorAll('.custom-radio input');
radios.forEach(radio => {
radio.addEventListener('change', () => {
radios.forEach(r => r.checked = false);
radio.checked = true;
});
});
领取专属 10元无门槛券
手把手带您无忧上云