微信小程序基础-高亮切换

118 阅读1分钟

思路:先在js中声明好要展示的数据datalist和使用到的数据current,于是在wxml中利用wx:for遍历datalist,其中wx:key表示键值索引,接着用data-myid绑定datalist的索引值,只有绑定了,才能通过绑定事件handleTap将e.target.dataset.myid赋给current,从而利用class里的三目运算符来控制是否高亮显示。

注意:class="item {{current == index? 'active':''}}" 中item 和大括号之间存在空格,否则无法显示高亮

代码示例如下

highlight.wxml

<view class="box">
  <view wx:for="{{datalist}}" 
  wx:key="index" 
  data-myid="{{index}}"
  bindtap="handleTap"
  class="item {{current == index? 'active':''}}" 
  >
   <text data-myid="{{index}}"> {{item}}</text>
  </view>
</view>

highlight.js

Page({
    data: {
        datalist:['衣服','裤子','鞋子'],
        current:0
      },
      handleTap(e){
      //可以打印查看e里面有没有自己想要的数据
        console.log(e.target.dataset.myid);
        this.setData({
          current:e.target.dataset.myid
        })
      }
})

highlight.css

.box{
  display: flex;
  flex-direction: row;
}
.box .item{
 flex:1;
 text-align: center;
}
.box .active{
  font-size: 16px;
  color: #ff6700;
}

成果显示

image.png