一、js
data: { host: getApp().globalData.baseUrl, carouselList:[], }, onLoad: function (options) { this.requestCarouselListData();//請求輪播圖 }, //請求輪播圖 requestCarouselListData(){ var that = this;//注意this指向性問題 var urlStr = that.data.host + "/xjj/chome_carousel_list.json"; //請求連接注意替換(我用本地服務(wù)器模擬) console.log("請求輪播圖:" + urlStr); wx.request({ url: urlStr, data: {//這里放請求參數(shù),如果傳入?yún)?shù)值不是String,會被轉(zhuǎn)換成String // x: '', // y: '' }, header: { 'content-type': 'application/json' // 默認(rèn)值 }, success(res) { console.log("輪播圖返回值:"); console.log(res.data.result); var resultArr = res.data.result; that.setData({ carouselList: resultArr }) } }) }, //點擊了輪播圖 chomeCarouselClick: function (event) { var urlStr = event.currentTarget.dataset.url; console.log("點擊了輪播圖:" + urlStr); // wx.navigateTo({ // url: 'test?id=1' // }) }, |
2. wxml
<!-- 輪播圖 --> <view class='carousel'> <swiper class='carousel_swiper' indicator-dots="true" indicator-color="#f4f4f4" indicator-active-color="#4eb8b8" autoplay="true" interval='2000' circular='true'> <block wx:for="{{carouselList}}" wx:key="key"> <swiper-item bindtap='chomeCarouselClick' data-url='{{item.url}}'> <image class="carouselImg" src='{{host}}{{item.img}}' mode='aspectFill' ></image> </swiper-item> </block> </swiper> </view> /*幾個有用的說明: indicator-dots 是否顯示指示器 indicator-color 指示器默認(rèn)顏色 indicator-active-color 指示器選中顏色 autoplay 是否自動播放 interval 每一頁停留的時長 circular 播放到最后一頁后是否再銜接第一頁循環(huán)播放 */ |
三、wxss
page { //這個是當(dāng)前頁整體的背景色 background-color: #f4f4f4; } .carousel{ width: 100%; background-color: rebeccapurple; } .carousel_swiper{ width: 100%; height: 400rpx; display: block; position: relative; background: #f4f4f4; } .carouselImg{ width: 100%; height: inherit; } |
運行截圖.png
附件
本地服務(wù)器 輪播圖的數(shù)據(jù) chome_carousel_list.json { "result": [{ "id": "101", "img": "/xjj/img/carousel_1.png", "title": "", "url": "https://www.baidu.com/" }, { "id": "102", "img": "/xjj/img/carousel_2.png", "title": "百度翻譯", "url": "https://fanyi.baidu.com/" }, { "id": "103", "img": "/xjj/img/carousel_3.png", "title": "百度地圖", "url": "https://map.baidu.com/" }, { "id": "104", "img": "/xjj/img/carousel_4.png", "title": "簡書是一個寫博客的網(wǎng)站,挺好用的,可以試試看", "url": "https://www.jianshu.com/" } ] } |