(四)微信小程式--輪播圖swiper元件實現及Boolean值陷阱
阿新 • • 發佈:2018-12-11
輪播圖 swiper 元件
前期需要的搭建
- 將需要輪播的圖片儲存到
/images/post/
目錄下,沒有就建立它 - 在pages目錄下新建一個名為post的目錄,然後在post目錄下新建頁面所需要的4個檔案post.js, post.json, post.wxml, post.wxss 每個檔案所需要的程式碼在我前序文章中有提到 從零開始新建一個專案
- 在
app.json
的pages數組裡追加post頁面路徑,但需是pages資料第一個元素,位於welcome頁面之前
{
"pages":[
"pages/post/post",
"pages/welcome/welcome"
],
"window":{
"navigationBarBackgroundColor":"#ECC0A8"
}
}
- 儲存並執行,執行效果如下
post.wxml 檔案中新增swiper元件(滑動檢視容器)
<view> <!--作為整個網頁的容器-->
<swiper>
<swiper-item>
<image src="../../images/post/post-1.jpg"></image>
</swiper-item>
< swiper-item>
<image src="../../images/post/post-2.jpg"></image>
</swiper-item>
<swiper-item>
<image src="../../images/post/post-3.jpg"></image>
</swiper-item>
</swiper>
</view>
swiper元件的直接子元素只可以是swiper-item,若放置其他元件,則會被自動刪除,但swiper-item下是可以放置其他元件或者元素的
post.wxss 中新增swiper元件和image元件樣式
swiper{ /*設定swiper元件的寬度和高度*/
width:100%;
height:600rpx;
}
swiper image{ /*設定image元件的樣式*/
width:100%;
height:600rpx;
}
需要同時設定swiper元件樣式和image元件樣式的高度,才能達到預期的效果
儲存並執行,執行效果如下:
我們來看一下,只設置其中某個樣式和全不設的效果 ,滑鼠移動到圖片中心即看到圖片標題
給swiper元件新增屬性實現輪播效果
更新post.wxml
中程式碼內容如下:
<view> <!--作為整個網頁的容器-->
<swiper indicator-dots="ture" autoplay="true" interval="5000" circular="true">
<swiper-item>
<image src="../../images/post/post-1.jpg"></image>
</swiper-item>
<swiper-item>
<image src="../../images/post/post-2.jpg"></image>
</swiper-item>
<swiper-item>
<image src="../../images/post/post-3.jpg"></image>
</swiper-item>
</swiper>
</view>
swiper元件屬性
indicator-dots
預設false
,用來指示是否顯示面板指示點,Boolean型別
autoplay
預設false
,用來決定是否自動播放,Boolean型別
interval
預設5000毫秒
,用來設定swiper-item的切換時間,Number型別
circular
預設false
, 迴圈滾動
vertical
用來指明面板指示點的排布方式是水平還是垂直,Boolean型別
Boolean值的陷阱
- 面板指示點水平
不加入vertical屬性
vertical=""
vertical="{{false}}"
以上三種寫法將vertical屬性設定成false
執行效果如圖: - 面板指示點垂直
vertical="true"
vertical="false"
vertical="aaa"
vertical="bbb"
這裡的false並不是並不是Boolean型別,而是一個字串,只要不為空字串,在javaScript裡都會被認為是一個true,vertical屬性被設定為true
執行效果如下