【微信小程式開發】實現輪番圖效果swiper 元件
阿新 • • 發佈:2019-01-24
輪番效果在很多的網站主頁或者手機應用端都能看到,在微信小程式中使用swiper元件來實現圖片輪番,今天的小例子效果如下:
為了方便演示我將動畫切換的間隔調整為3s,現實專案中一般為5s,具體看專案需求而定。
實現圖片輪番使用swiper滑塊檢視容器元件,頁面結構檔案程式碼如下:
<!--mySwiper.wxml-->
<view class="container">
<swiper indicator-dots="{{indicatorDots}}"
autoplay="{{autoplay}}" interval="{{interval }}" duration="{{duration}}">
<block wx:for="{{imgUrls}}">
<swiper-item>
<image src="{{item}}" class="slide-image" width="355" height="150"/>
</swiper-item>
</block>
</swiper>
</view>
忽略最外層的父容器view和元件屬性,頁面檔案結構簡化如下:
<swiper >
<block wx:for="{{imgUrls}}">
<swiper-item>
<image/>
</swiper-item>
</block>
</swiper>
以上程式碼看出,整個輪番圖的程式碼是有一個swiper元件,包含著多個swiper-item元件形成的,其中swiper-item中放置的是image。
的作用是控制屬性繫結一個imgUrls陣列,使用陣列中各項的資料重複渲染該元件。block標籤並不會在頁面中渲染,如需瞭解更多可進入官方文件:程式碼中看到 的 {{}} 符號是Mustache
語法,意思是將雙大括號中的變數名中的資料取出,實現資料繫結,這些變數在同名檔案的.js檔案中data物件中宣告,如下:
// mySwiper.js
Page({
data:{
imgUrls: [
'/asserts/img/001.jpg',
'/asserts/img/002.jpg',
'/asserts/img/003.jpg'
],
indicatorDots: true,
autoplay: true,
interval: 3000,
duration: 1000
},
onLoad:function(options){
// 生命週期函式--監聽頁面載入
}
}
其中,
indicator-dots: 是否顯示面板指示點,預設為false;
autoplay:是否自動切換,預設為false;
interval:自動切換時間間隔,預設5000ms;
duration: 滑動動畫時長,預設為1000ms;
需要注意的是swiper元件需要給他一個寬度,不然swiper不顯示,這裡給了一個具體的寬高,並設定居中顯示:
/* pages/mySwiper/mySwiper.wxss */ swiper{
margin: 0 auto;
height: 200px;
width: 300px; }
詳細swiper屬性說明如下: