在有些項目中都會用到swiper這個元件,下面給大家分享一個輪播圖的效果,效果如下圖
-
帶你玩轉輪播圖 - js如下
-
Page({ data: { images: [ { imgUrl: '/image/1.jpg' }, { imgUrl: '/image/2.jpg' }, { imgUrl: '/image/3.jpg' }, { imgUrl: '/image/4.jpg' }, ], indicatorDots: true, autoplay: true, interval: 3000, current: 1 //預設顯示第幾張,0為第一張 }, changeimage(e) { var num = e.detail.current; var source = e.detail.source; this.setData({ current: num, }) console.log(num, source) }, })
- axml如下:
-
- acss如下:
-
/* 通過樣式來調整圖檔大小與擺放位置,已經加上動态效果 */ .swiper{ height: 408rpx!important; } .a-swiper-item{ width: 100%; height: 340rpx; } .active{ width: 640rpx!important; transition: 0.5s all linear; margin-left: 56rpx; } .before{ width: 540rpx!important; transition: 0.5s all linear; margin-left: 230rpx; margin-right: -24rpx; } .after{ width: 540rpx!important; transition: 0.5s all linear; margin-left: -24rpx; } .page_top{ height: 484rpx; } .card_box{ padding-top:24rpx; height: 432rpx; } .card_box .a-image{ width: 640rpx; height: 340rpx; }
- 這樣就可以實作圖中的輪播效果了。
- 注意:如果該swiper中的圖檔背景是通過接口擷取的,在寫代碼的時候請把需要輪播的元素給個預設值,最好有兩個以上的元素,這樣就可以避免在擷取接口資料過來輪播圖需要手動去滑一下才能自動播放。