我們經常看到,在小程序中包含循環滾動播放的輪播圖片,這是怎么做的呢,這篇文章我就帶大家來完成一下,這個功能。
先來看看完成的效果圖:
從效果圖中,我們可以看到,有3張圖輪播,點擊輪播圖片,當前頁面還可以做出響應。
首先在項目根目錄建立images文件夾,並將准備好3張圖片,放在其中。具體如圖:
具體參考代碼:
js文件代碼:
Page({ /** * 頁面的初始數據 */ data: { imageItems: [{ id: 1, imgsrc: "../../images/1.png", link: "http://www.test.com/id=1" }, { id: 2, imgsrc: "../../images/2.png", link: "http://www.test.com/id=2" }, { id: 15, imgsrc: "../../images/15.png", link: "http://www.test.com/id=15" }], info:"" }, /*點擊圖片事件處理函數 */ imgTap: function (params) { /** * params代表傳過來的參數集合 * 在wxml頁面是通過data-**格式傳過來 * 在js函數中通過 params.currentTarget.dataset.**方式來獲取 */ /**在調試器控制台輸出傳過來參數link */ console.info(params.currentTarget.dataset.link); /**通過小提示方式顯示傳過來參數id * 需要注意的是,title只能接受string類型值,由於id是整數,故我們需要利用+""的方法來進轉換 */ wx.showToast({ title: params.currentTarget.dataset.id+"", }) /**下面的代碼展示了如何動態設定data的值 * 將info的值設置為傳過來參數 link */ this.setData({ info: params.currentTarget.dataset.link }) } })
wxss文件代碼:
.swiperItem { width: 100%; height: 500rpx; }
wxml文件代碼:
<swiper class="swiperItem" indicator-dots="true" indicator-color="rgba(0,0,0,.3)" autoplay="true" interval="5000" duration="1000" circular="true"> <block wx:for="{{imageItems}}" wx:key="*this" wx:for-item="img"> <swiper-item> <image class="swiperItem" bindtap="imgTap" data-link="{{img.link}}" data-id="{{img.id}}" src="{{img.imgsrc}}" mode="aaspectFill" lazy-load="false"> </image> </swiper-item> </block> </swiper> <text style="color:red;width:100%;height:50rpx">{{info}}</text>
微信小程序輪播圖片,為我們提供了現成的組件swiper。
swiper主要屬性說明:
indicator-dots:是否顯示輪播指示器,即下面的小圓點
autoplay:是否自動播放
interval:各個圖片切換時間間隔,單位毫秒
duration:切換耗時,單位毫秒
其他具體用法,查看文檔吧,寶貝們。
https://developers.weixin.qq.com/miniprogram/dev/component/swiper.html
主要說明:
bindtap是綁定事件,imgTap是在js文件中做的事件響應函數
data-* * 是為了通過事件傳參數,參數名即為 * *,本例傳了2個參數,link與id
OK!輪播講完,收! 有問題,留言!