微信小程序開發實現輪番圖效果swiper 組件

輪番效果在很多的網站主頁或者手機應用端都能看到,在微信小程序中使用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標籤並不會在頁面中渲染,如需瞭解更多可進入官方文檔:

https://mp.weixin.qq.com/debug/wxadoc/dev/framework/view/wxml/list.html?t=201715
中瞭解更多關於 block wx:for 的內容。

代碼中看到 的 {{}} 符號是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屬性說明如下:
這裏寫圖片描述

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