小程序官方本提供了该组件的使用,但是扩展性不太好,为了防止和CheckBox混淆,所以单独剔分出来
一 、HTML
<view wx:for="{{radio}}" wx:key="{{*this}}" class="checkbox '{{item.checked?'checkedActive':''}}'" data-id="{{index}}" bindtap='getradio'>
<text>{{item.value}}</text>
</view>二、CSS
.checkbox {
display: inline-block;
padding: 10rpx;
background: #eee;
margin: 10rpx;
border-radius: 10rpx;
}
.checkedActive {
background: red;
color: #fff;
}三、JS
Page({
data:{
radio:[
{ 'value': '北京'},
{'value':'广州'},
{'value':'上海'},
{'value':'沈阳'}
]
},
//单选
getradio:function(e){
let index = e.currentTarget.dataset.id;
let radio = this.data.radio;
for(let i=0; i<radio.length; i++){
this.data.radio[i].checked = false;
}
if (radio[index].checked){
this.data.radio[index].checked = false;
}else{
this.data.radio[index].checked = true;
}
let userRadio = radio.filter((item,index)=>{
return item.checked == true;
})
this.setData({radio:this.data.radio})
console.log(userRadio)
}
})四、
*选中效果

*选中数据

五、
本文介绍了一种在小程序中实现自定义单选框的方法,包括HTML结构、CSS样式及JavaScript交互逻辑,使得用户可以更好地控制组件的表现和行为。
1500

被折叠的 条评论
为什么被折叠?



