微信小程序中动态添加删除class类名 使用三元表达式动态设置标签的class名

目的,在微信小程序的swiper中达到除了active的哪一项外的其他项都有一个半透明的白色浮层。
效果图 如下:

效果图

功能实现:
我们使用三元表达式即可实现动态设置标签中的class属性 如下:
<view class='{{index != swiperIndex ? "swiper-small" : ""}}'>
上面这段代码里,有两个变量,当index的值与swiperIndex的值不想等的时候,此标签的class为swiper-small否者为""空。
该Demo的完整代码如下:
<!-- wxml -->
<swiper indicator-dots="{{ false }}" display-multiple-items="1" circular="{{ true }}" next-margin="50rpx" previous-margin="50rpx" class="swiper" bindchange="swiperChange">
  <block wx:for="{{imgUrls}}">
    <swiper-item style="position: absolute; width: 100%; height: 400rpx; transform: translate(0%, 0px) translateZ(0px);">
      <view class='{{index != swiperIndex ? "swiper-small" : ""}}'>
        <image src="{{item}}" class="slide-image" width="355" height="150"/>
        <view class="swiper-top" wx:if="{{ index != swiperIndex }}"></view>
      </view>
    </swiper-item>
  </block>
</swiper>
/* wxss */
.slide-image {
  position: absolute;
  top: 0;
  width: 100%;
  height: 400rpx;
}
.swiper-small {
  position: absolute;
  width: 100%;
  height: 80%;
  top: 50%;
  transform: translateY(-50%);
  -webkit-transform: translateY(-50%);
  opacity: 0.8;
  overflow: hidden;
}
.swiper-top {
  position: absolute;
  top: 0;
  width: 100%;
  height: 400rpx;
  background-color: rgba(255, 255, 255, 0.5);
}
.swiper {
  width: 100%;
  height: 400rpx;
}
/* js */
Page({
  data: {
    imgUrls: [
      'https://images.unsplash.com/photo-1551334787-21e6bd3ab135?w=640',
      'https://images.unsplash.com/photo-1551214012-84f95e060dee?w=640',
      'https://images.unsplash.com/photo-1551446591-142875a901a1?w=640'
    ],
    swiperIndex: 0,
  },
  swiperChange: function (e) {
    console.log('e', e.detail.current)
    this.setData({
      swiperIndex: e.detail.current
    })
  },
})
每个功能的需求都不一样,请根据实际需求进行修改。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值