微信小程序:轮播图居中高亮显示

时间:2024-05-19 12:56:11
  1. 效果展示:微信小程序:轮播图居中高亮显示
  2. test.wxml:
<swiper display-multiple-items='1' current='{{ centerItem }}' bindchange='changeFun' circular='true'
  previous-margin='50' next-margin='50' autoplay='true' interval='2000'>
  <block wx:for="{{imgInfoArr}}">
    <swiper-item>
      <view class='optionBox' style='text-align:center'>
        <view class='mask' wx:if='{{ index != centerItem }}'></view>
        <image src="{{item.src}}" mode='aspectFit' />
        <view class='swiperText' style='font-size:0.5em;'>{{ item.text }}</view>
      </view>
    </swiper-item>
  </block>
</swiper>
  1. test.wxss:
swiper{
  height: 200px;
}
.optionBox {
  width: 100%;
  height: 90%;
}
.optionBox image {
  width: 100%;
  height: 100%;
}
.swiperText {
  width: 100%;
  height: 25px;
  text-align: center;
  font-family: bariol_bold;
  font-size: 0.5em;
  color: #4a4a4a;
}

.mask {
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, .5);
  position: absolute;
  left: 0;
  top: 0;
}

.perch {
  width: 100%;
  height: 100%;
}
  1. test.js:
// text/text.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgInfoArrLength: 0,  // 轮播图列表的长度
    centerItem: 0,  // 居中项的位置
    imgInfoArr: [
      {
        src: 'https://qidian.qpic.cn/qidian_common/349573/16af4f9cfd8b15a6cea1df7eea361a91/0',
        text: '测试数据',
        id: 0
      },
      {
        src: 'https://qidian.qpic.cn/qidian_common/349573/e1f9f863e6f8fe99c9002e88eb96326b/0',
        text: '测试数据',
        id: 1
      },
      {
        src: 'https://qidian.qpic.cn/qidian_common/349573/6805566e37fae69d0be5677f5367889a/0',
        text: '测试数据',
        id: 2
      },
      {
        src: 'https://ss.****.net/p?https://mmbiz.qpic.cn/mmbiz_png/BnSNEaficFAbJfLOWW20jLyVL68E32lCc9JE57rVYUqicOAKCFrYXVXofexRdaCibq0J3SuJuibdszBibZOTGIiaicPKw/640?wx_fmt=png',
        text: '测试数据',
        id: 3
      },
      {
        src: 'https://ss.****.net/p?https://mmbiz.qpic.cn/mmbiz_gif/BnSNEaficFAbJfLOWW20jLyVL68E32lCc4oPRHTMUvsxSkadf7oRytn7aZToR8oMkWJbZ6Qq7F99ibIBE7PFD6Ag/640?wx_fmt=gif',
        text: '测试数据',
        id: 4
      },
      {
        src: 'https://ss.****.net/p?https://mmbiz.qpic.cn/mmbiz_png/BnSNEaficFAbJfLOWW20jLyVL68E32lCcicCUo1ZoUIA4YBM9gezJOaZrJxumnaOYqlgP4bnibpuvzw0AVZ7viaIwg/640?wx_fmt=png',
        text: '测试数据',
        id: 5
      },
      {
        src: 'https://ss.****.net/p?https://mmbiz.qpic.cn/mmbiz_png/BnSNEaficFAbJfLOWW20jLyVL68E32lCccUNarh5lcPuQwtGUniaS1F8b8Mmu9jOhmVF5nIWISeegdV0Kiarbg1OA/640?wx_fmt=png',
        text: '测试数据',
        id: 6
      }
    ],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var len = this.data.imgInfoArr.length;
    var center = parseInt(len/2);
    this.setData({
      imgInfoArrLength: len,
      centerItem: center
    })
  },

  changeFun(e) {
    this.setData({
      centerItem: e.detail.current,
    })
  }
})