微信小程序自定義swiper的底部指示點(指示點不在swiper元素裏面)

實現一個小程序swiper指示點在下方的一個demo,並且在每張圖片上有對應的文字釋義。

效果圖:
在這裏插入圖片描述

注意:代碼是用mpvue框架寫的,跟原生的有所不同,但是原理是一樣的,都是用小程序提供的一個事件。原生也就是設置值和綁定動態樣式不一樣。

在這裏插入圖片描述
原生使用的注意點
在這裏插入圖片描述
最開始本來打算用css控制樣式來實現,然後發現超出swiper元素內容會被隱藏,然後試了下,感覺有點麻煩,發現組件有提供一個事件給我,然後可以利用這一個事件,直接定義一個指示點。感覺這樣更加直接,所以用的這個方式。

上代碼

<template>
  <div>
    <swiper
      autoplay="true"
      circular="true"
      @change="swiperChange"
    >
      <template v-for="(item, i) in swiperData">
        <swiper-item>
          <img
            @change="imgChange"
            :src="item.img"
            class="indexItem"
            mode="aspectFill"
          />
          <p class="swiper-itemText">{{item.text}}</p>
        </swiper-item>
      </template>
    </swiper>
    <!-- 自定義指示點dot -->
    <div class="customDots">
      <template v-for="(item, index) in swiperData">
        <div class="customDots-item" :class="{ active: swiperCurrent == index }"></div>
      </template>
    </div>
  </div>
</template>

js

<script>
export default {
  data() {
    return {
      swiperData: [        {
          img: "https://cdn.pixabay.com/photo/2020/03/18/05/29/swimming-pool-4942724__340.jpg",
          text: '嘟嘟第一張'
        },
         {
          img: "https://cdn.pixabay.com/photo/2020/04/02/11/20/fungus-4994622__340.jpg",
          text: '啦啦第二張啦啦第二張啦啦第二張啦啦第二張啦啦第二張'
        },
         {
          img: "https://cdn.pixabay.com/photo/2017/12/29/10/23/nature-3047194__340.jpg",
          text: '嘿嘿第三張'
        }
      ],
      swiperCurrent: 0,
    };
  },
  methods: {
     //自動滑動時,獲取當前的輪播對象  原生的這裏設置值不一樣
    swiperChange(e) {
      this.swiperCurrent = e.mp.detail.current
    },
    //圖片手動滑動時,獲取當前的輪播對象
    imgChange(e) {
      this.swiperCurrent = e.mp.detail.current
    }
  },
};
</script>

css

<style scoped>
swiper {
  width: 100%;
  height: 388rpx;
}

swiper-item {
  border-radius: 14rpx;
  overflow: hidden;
  position: relative;
  width: 100%;
  height: 388rpx;
}
.indexItem {
  width: 100%;
  height: 388rpx;
}

.swiper-itemText {
  position: absolute;
  left: 34rpx;
  bottom: 24rpx;
  font-size: 32rpx;
  width: 80%;
  color: red;
  overflow: hidden;
  text-overflow:ellipsis;
  white-space: nowrap;
}
.customDots {
  margin-top: 20rpx;
  display: flex;
  justify-content: center;
}
/* 不是當前狀態的點 */
.customDots .customDots-item {
  margin: 0 8rpx;
  width: 14rpx;
  height: 14rpx;
  background-color: transparent;
  border-radius: 8rpx;
  background:red;
  transition: all 0.6s ease-in-out;
}
/* 當前顯示點 */
.customDots .customDots-item.active {
  width: 30rpx;
  background: red;
}
</style>

做完後發現還有一種思路,讓img的高小點,swiper-item的高高些,然後原本的指示點自熱而然好像也變成這個效果。不過後面沒去試下了,有興趣的可以試下。可以的話留言下,感覺這個好像更簡單些。還不需要寫這麼多,尷尬。

個人水平有限,有問題歡迎大家留言指導,僅供學習和參考。

學海無涯!努力二字,共勉!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章