輪播圖是大部分應用的一個常用的功能,常用于廣告投放、產品展示、活動展示等等。
漂亮的輪播圖效果可以吸引用戶的點擊,達到推廣產品的作用。
廢話少說,下面開始動手。
業務需求:
5個圖片輪番播放,可以左右滑動,點擊指示點可以切換圖片
重點說明:
由于微信小程序,整個項目編譯后的大小不能超過1M
查看做輪播圖功能的一張圖片大小都已經有100+k了
那么我們可以把圖片放在服務器上,發送請求來獲取。
index.wxml:
這里使用小程序提供的<swiper>組件
autoplay:自動播放
interval:自動切換時間
duration:滑動動畫的時長
current:當前所在的頁面
bindchange:current 改變時會觸發 change 事件
由于<swiper>組件提供的指示點樣式比較單一,另外再自定義指示點的樣式
<view class="recommend" > <view class="swiper-container"> <swiper autoplay="auto" interval="5000" duration="500" current="{{swiperCurrent}}" bindchange="swiperChange" class="swiper"> <block wx:for="{{slider}}" wx:key="unique"> <swiper-item data-id="{{item.id}}" data-url="{{item.linkUrl}}"> <image src="{{item.picUrl}}" class="img"></image> </swiper-item> </block> </swiper> <view class="dots"> <block wx:for="{{slider}}" wx:key="unique"> <view class="dot{{index == swiperCurrent ? ' active' : ''}}" bindtap="chuangEvent" id="{{index}}">{{index+1}}</view> </block> </view> </view> </view>
index.wxss:
.swiper-container{ position: relative; } .swiper-container .swiper{ height: 300rpx; } .swiper-container .swiper .img{ width: 100%; height: 100%; } .swiper-container .dots{ position: absolute; right: 40rpx; bottom: 20rpx; display: flex; justify-content: center; } .swiper-container .dots .dot{ margin: 0 10rpx; width: 28rpx; height: 28rpx; background: #fff; border-radius: 50%; transition: all .6s; font: 300 18rpx/28rpx "microsoft yahei"; text-align: center; } .swiper-container .dots .dot.active{ background: #f80; color:#fff; }
index.js:
//導入js var util = require('../../utils/util.js') Page({ data: { slider: [], swiperCurrent: 0 }, onLoad: function () { var that = this; //網絡訪問,獲取輪播圖的圖片 util.getRecommend(function(data){ that.setData({ slider: data.data.slider }) }); }, //輪播圖的切換事件 swiperChange: function(e){ //只要把切換后當前的index傳給<swiper>組件的current屬性即可 this.setData({ swiperCurrent: e.detail.current }) }, //點擊指示點切換 chuangEvent: function(e){ this.setData({ swiperCurrent: e.currentTarget.id }) } })
utils.js:
//網絡訪問 function getRecommend(callback) { wx.request({ url: 'https://c.y.qq.com/musichall/fcgi-bin/fcg_yqqhomepagerecommend.fcg', data: { g_tk: 5381, uin: 0, format: 'json', inCharset: 'utf-8', outCharset: 'utf-8', notice: 0, platform: 'h5', needNewCode: 1, _: Date.now() }, method: 'GET', header: {'content-Type': 'application/json'}, success: function(res){ if(res.statusCode == 200){ callback(res.data); } } }) } module.exports = { getRecommend: getRecommend }
運行:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答