微信小程序切换列表颜色的转换
index.wxml:
<view class='style {{item.id==num?"active":""}}' catchtap='clickList' wx:for="{{message}}" wx:key="" data-num="{{item.id}}">{{item.text}}</view>
index.wxss:
.style {
width: 200rpx;
height: 100rpx;
}
.active{
color: red
}
index.js:
// pages/index/index.js
Page({
/**
* 页面的初始数据
*/
data: {
num:1,
message:[
{
id:'1',
text:"今日头条"
},
{
id: '2',
text:'趣头条'
},
{
id: '3',
text: '百家号'
},
{
id:'4',
text: '企鹅号'
},{
id:'5',
text:'大鱼号'
}
]
},
clickList:function(e){
console.log(e)
let num = e.target.dataset.num
this.setData({
num:num
})
console.log(this)
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})
为你需要点击的列表加上点击事件,使用data-id将id传到点击事件中
然后将获取到的这个值传到num中setData到Data中,然后当item.id==num
那么就加上这个active类,如果不是就为空,默认的话讲data中的num:1
,默认的那一个就会被选中。