【微信小程序】自定义单选框样式实现单选功能

这篇博客介绍了如何在微信小程序中实现点击选择小车时,其他车辆类型自动取消选中的功能。通过使用数组存储不同类型的车辆数据,并设置每个条目的checked属性来控制选中状态。当用户点击某个车辆类型时,更新该条目的checked状态,同时遍历数组取消其他项的选中状态。示例代码包括JavaScript和WXML结构,以及对应的CSS样式,展示了具体的实现细节。
摘要由CSDN通过智能技术生成

实现效果:

选择小车时,其他类型的车取消选中。

在这里插入图片描述

具体思路:

用数组存几种类型车的数据,给每条数据设置点击未选中的效果(checked 设为 false)。点击某一种车时,获取其下标,将它的设置为选中(checked 设置 true)。

代码如下:

// index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    list: [{
        img: "../../image/car.png",
        name: "小车",
        type: "C1/C2/C3",
        checked: true,
      },
      {
        img: "../../image/trucks.png",
        name: "货车",
        type: "A2/B2",
        checked: false,
      },
      {
        img: "../../image/passenger-car.png",
        name: "客车",
        type: "A1/A3/B1",
        checked: false,
      },
      {
        img: "../../image/motorbike.png",
        name: "摩托车",
        type: "D/E/F",
        checked: false,
      }
    ],
  },

  // 选择
  choose: function (e) {

    let index = e.currentTarget.dataset.id;
    let list = this.data.list;
    for (let i = 0; i < list.length; i++) {
      this.data.list[i].checked = false;
    }
    if (list[index].checked) {
      this.data.list[index].checked = false;
    } else {
      this.data.list[index].checked = true;
    }
    this.setData({
      list: this.data.list
    })
  },

})
<!-- wxml -->
  <view class="chooseType" >

    <view class=" {{item.checked?'chooseType-content-select':'chooseType-content'}}'" wx:for="{{list}}" wx:key="index" data-id="{{index}}" bindtap="choose">
      <image class="chooseType-content-img" src="{{item.img}}"></image>
      <view>{{item.name}}</view>
      <view class="chooseType-content-type">{{item.type}}</view>
    </view>

  </view>

 /* wxss */
.chooseType {
  width: 100%;
  height: 200rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: rgb(197, 196, 187) 1rpx solid;
  font-size: 30rpx;
  background: #FFFFFF;
}

.chooseType-content-img{
  width: 90rpx;
  height: 90rpx;
}


.chooseType-content{
  width: 25%;
  height: 100%;
  display: flex;
  align-items: center;
  flex-direction: column;
}

.chooseType-content-select{
  width: 25%;
  height: 100%;
  display: flex;
  align-items: center;
  flex-direction: column;
  background: rgb(163, 162, 162,0.2);
}

.chooseType-content-type{
  margin-top: 10rpx;
  font-size: 30rpx;
  color: #b3b0b0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值