1. 程式人生 > >微信小程式左右滑動切換圖片酷炫效果(附效果)

微信小程式左右滑動切換圖片酷炫效果(附效果)

開門見山,先上效果吧!感覺可以的用的上的再往下看。(動圖網址)

  心動嗎?那就繼續往下看!

  先上頁面結構吧,也就是wxml檔案,其實可以理解成微信自己封裝過的html,這個不多說了,不懂也沒必要往下看了。

  1. 1<scroll-view class="scroll-view_H" scroll-x scroll-with-animation style="width: 100%;height:{{windowHeight}}px" bindscroll="getSelectItem">
  2. 2<block wx:for="{{proList}}" wx:key="unique"
    wx:for-index="id" wx:for-item="item">
  3. 3<view class="scroll_item {{item.selected ? 'selected' : ''}}" data-index='{{item.index}}' bindtap='selectProItem'>
  4. 4<view class='proImg'><image src="{{item.proUrl}}"class="slide-image" mode="widthFix"/></view>
  5. 5<view class='detailBox'
    >
  6. 6<view class='proTitle'>{{item.proTitle}}</view>
  7. 7<view class='proDec'>{{item.proDec}}</view>
  8. 8<view class='proPrice'>¥{{item.proPrice}}</view>
  9. 9<navigator class='detailLink' url="../detail/detail?id={{item.id}}">檢視詳情></navigator>
  10. 10</view>
  11. 11</view
    >
  12. 12</block>
  13. 13</scroll-view>

  做該效果樣式就不多說了,一個預設狀態樣式,一個當前選中樣式。(開發小程式的時候,注意class的命名,儘量不要使用層級巢狀,所以class取名的時候要注意唯一性)

  • View Code 
      

      js部分:該效果基於小程式的元件 scroll-view 開發的,利用bindscroll事件載入回撥函式。

      回撥事件原理:

      通過滾動寬度和每個item的寬度從而獲取當前滾動的item是第幾位,然後給對應的item加上選中class,其他的則去除選中class。

  1. //滑動獲取選中商品
  2. getSelectItem:function(e){
  3. var that =this;
  4. var itemWidth = e.detail.scrollWidth / that.data.proList.length;//每個商品的寬度
  5. var scrollLeft = e.detail.scrollLeft;//滾動寬度
  6. var curIndex =Math.round(scrollLeft / itemWidth);//通過Math.round方法對滾動大於一半的位置進行進位
  7. for(var i =0, len = that.data.proList.length; i < len;++i){
  8. that.data.proList[i].selected =false;
  9. }
  10. that.data.proList[curIndex].selected =true;
  11. that.setData({
  12. proList: that.data.proList,
  13. giftNo:this.data.proList[curIndex].id
  14. });
  15. },

  ps:有時候一些酷炫的效果其實實現起來非常簡單,建議開發前先理清實現思路,雖然整個文章言簡意賅,能看懂就自然懂,樂在分享。