小程序之圖片瀑布流(最全實現方式,額外加送懶加載)

效果圖

來來來,看啊看,外面的世界多好看,

image

效果圖展示的是瀑布流布局 && 懶加載的效果

數據

圖片數據來源張鑫旭的網絡日志

先說下我們的圖片鏈接格式

所有的鏈接都是http://cued.xunlei.com/demos/publ/img/P_${name}.jpg這樣的格式,我們需要改變name的值就行了,當name值小于10的時候,格式是00x,如002003,大于10的時候就是023這種。

定義

瀑布流布局是一種比較流行的頁面布局方式, 最早采用此布局的網站是Pinterest, 圖片寬度是固定的,高度自動,產生一種參差不齊的美感。

原理

原理很簡單,主要分為以下幾步

1、定義高度數組和列數

2、遍歷元素,個數小于列數的直接push到數組中

3、大于列數的,獲取高度數組中最小的值,定義元素的top和left值

4、重要一點 更新高度數組,將最小高度加上當前元素的高度

知道原理了,代碼應該怎么寫呢?這里用web端來示例,大概如下

let heightArr = []
let col = 2
let allBox = document.querySelectorAll('.box') // 獲取所有盒子

for(let i in allBox){
    
    let boxWidth = allBox[0].offsetWidth  // 獲取盒子寬度 都一樣直接取第一個
  let boxHeight = allBox[i].offsetHeight
    if(i < col){    
        heightArr.push(boxHeight)  // 把第一行高度都添加進去
    } else {  // 進行布局操作
        
        let minHeight = Mac.min.apply(null, heightArr)  // 獲取最小高度
        let minIndex = getIndex(heightArr, minHeight)  // 獲取最小高度的下標 要不就是0 要不就是1
        allBox[i].style.position = 'absolute'
        allBox[i].style.top = minHeight + 'px'
        allBox[i].style.width = minIndex * boxWidth + 'px'
        
        heightArr[minIndex] += boxHeight // 更新最新高度 
    }
}

// 獲取下標
getIndex(arr, val){
    for(i in arr){
        if(arr[i] == val) {
            return i
        }
    }
}

上面就是實現瀑布流的主要邏輯,這里大概寫了下,接下來我們看看小程序怎么實現。

實現

在web頁面里面我們可以直接獲取、操作DOM,實現起來很方便,何況還有很多的jquery插件可以使用。我們知道小程序里面是沒有DOM的,那應該怎么實現呢?我們把思路轉換下就行了。

這里我們用三種方式來實現瀑布流布局。

CSS

使用css3來實現是最簡單的,我們先撿簡單的來說,

使用column-count屬性設置列數

使用wx-if進行判斷將圖片渲染到左側還是右側

wxml

<view class='container'>
    <image src='{{item.url}}' wx:if="{{index % 2 != 0 }}" wx:for="{{list}}" mode='widthFix' wx:key="{{index}}"></image>
     <image src='{{item.url}}' wx:if="{{index % 2 == 0 }}" wx:for="{{list}}" mode='widthFix' wx:key="{{index}}"></image> 
</view> 

wxss

.container{
  column-count: 2;  /*設置列數*/ 
  column-gap:2rpx;
  padding-left: 8rpx;
}
image{
  width: 182px;
  box-shadow: 2px 2px 4px rgba(0,0,0,.4);
}

js獲取下數據即可,這里就不贅述了。

節點信息

小程序可以通過WXML節點信息API來獲取元素的信息,接下來我們來擼碼。

wxml

<view class="container">
      <view wx:for="{{group}}" style='position:{{item.position}}; top: {{item.top}}; left:{{item.left}}; width:{{width}}rpx;' class='box box-{{index}}' wx:key="{{index}}">
            <image  src='http://cued.xunlei.com/demos/publ/img/P_{{item.name}}.jpg' style=' height:{{height[index]}}px' bindload='load' data-index='{{index}}' class='image'></image>
      </view>
</view> 

wxss

.container{
  position: relative;
  display: flow-root;
}
.box{
  float: left;
  display: flex;
  margin-left:5rpx;
  box-shadow: 2rpx 2rpx 5rpx rgba(0,0,0,.3);
  border: 1rpx solid #ccc;
  box-sizing: border-box;
  padding: 10px;
}
.box:nth-child(2){
  margin-left: 12rpx;
}
image{
  width: 100%;
}

js

圖片鏈接為http://cued.xunlei.com/demos/publ/img/P_${name}.jpg, 只需要更改name就行了

首先處理我們的數據

// 創建長度為30的數組
const mockData = () => {
  return Array.from(Array(30).keys()).map(item => {
    if (item < 10) {
      return '00' + item
    } else {
      return '0' + item
    }
  })

}
// 擴展成我們需要的數據
const createGroup = () => {
  let group = []
  let list = mockData()
  list.forEach(item => {
    group.push({ name: item, position: 'static', top: '', left: '' })
  })
  return group
}

然后進行瀑布流布局,主要代碼如下

load(e){  // 監聽圖片加載完 獲取圖片的高度
    this.setData({
      height: [...this.data.height, e.detail.height]
    })
    this.showImg()  // 調用渲染函數
},

showImg(){
    let height = this.data.height
    if (height.lenth != this.data.group .legth){  // 保證所有圖片加載完
      return
    }
    setTimeout(()=>{ // 異步執行
      wx.createSelectorQuery().selectAll('.box').boundingClientRect((ret) => {
        let cols = 2
        var group = this.data.group
        var heightArr = [];
        for (var i = 0; i < ret.length; i++) {
          var boxHeight = height[i]
          if (i < cols) {
            heightArr.push(boxHeight + 25)
          } else {
            var minBoxHeight = Math.min.apply(null, heightArr);
            var minBoxIndex = getMinBoxIndex(minBoxHeight, heightArr);
            group[i].position = 'absolute'
            group[i].top = `${minBoxHeight}px`
            group[i].left = minBoxIndex * this.data.width / 2 + 'px'
            group[i].left = minBoxIndex == 0 ?  minBoxIndex * this.data.width / 2 + 'px' : minBoxIndex * this.data.width / 2 + 5 + 'px'
            heightArr[minBoxIndex] += (boxHeight + 25)
          }
        }

        this.setData({
          group
        })
        wx.hideLoading()

      }).exec()
    }, 200)
    
  }

可以看到實現的邏輯和上面的大概類似,只不過這里我們修改的是數據,畢竟小程序是數據驅動的嘛。

這里主要我們監聽image組件的bindload事件來獲取每張圖片的高度,獲取了高度才能進行布局,大部分的時間也都用來加載圖片了,能不能優化呢?當然可以了,我們使用node把數據包裝下。

后端處理數據

上面我們說到在小程序內部獲取圖片的高度是個費力不討好的事,我們使用node來獲取圖片高度,然后包裝下再給小程序使用。

  • 使用request進行請求
  • 使用image-size獲取圖片的高度
  • 最后將獲取后將數據寫入文件,啟動一個服務提供接口

這里主要說下碰到的問題

1、request模塊的請求默認返回來的是個String類型的字符串,使用image-size模塊傳入的必須是Buffer,怎么破呢?在request請求中設置encodingnull即可

2、我們這里爬取了100張圖片,怎么保證都已經爬取完了呢?可以這樣寫

Promise.all(List.map(item => getImgData(item)))  // getImgData函數是獲取圖片的函數 會返回個promise

3、如果請求了幾次,發現有的圖片獲取不到了,報錯了,怎么回事呢,人家畢竟做了防爬的,恭喜你中獎了,換個ip再試吧(可以把代碼放在服務器上面,或者換個Wi-Fi),其實我們只需要爬一次就行,生成完文件還爬干嘛啊。

完整代碼請戳github

我們回到小程序,此時接口返回的數據如下

image

可以看到每個圖片都有高度了,接下來我們實現瀑布流布局,等下,我們搞下瀑布流布局的懶加載,關于小程序的懶加載,猛戳了解更多

怎么實現呢?主要分為兩步

1、將元素瀑布流布局

2、創建IntersectionObserver,進行懶加載

先開始我們的布局吧

wxml

<view class='container'>
  <view class='pic pic-{{index}}' wx:for="{{list}}" style="height:{{item.height}}px;left:{{item.left}}; top:{{item.top}}; position:{{item.position}}" wx:key="{{item.index}}">
    <image src='{{item.url}}' wx:if="{{item.show}}"></image>
    <view class='default' wx:if="{{!item.show}}"></view>
  </view>
</view>

上面我們使用wx-if通過show這個字段來進行判斷了圖片是否加載,

使用一個view組件用來占位,然后更改show字段就可以顯示圖片了

js

我們使用兩個for循環,先來進行布局

let cols = 2
    let list = this.data.list
    let heightArr = [];


    for(let i in list){
      var boxHeight = list[i].height
      if (i < cols) {
        heightArr.push(boxHeight + 5)
      } else {
        var minBoxHeight = Math.min.apply(null, heightArr);
        var minBoxIndex = getMinBoxIndex(minBoxHeight, heightArr);
        list[i].position = 'absolute'
        list[i].top = `${minBoxHeight}px`
        list[i].left = minBoxIndex * 182 + 'px'
        list[i].left = minBoxIndex == 0 ? minBoxIndex * 182 + 'px' : minBoxIndex * 182 + 4 + 'px'
        heightArr[minBoxIndex] += (boxHeight + 5)
      }
    }
    this.setData({
      list
    })

布局完后,創建IntersectionObserver,動態判斷image節點的顯示

for (let i in list) {
      
    wx.createIntersectionObserver().relativeToViewport({ bottom: 20 }).observe('.pic-' + i, (ret) => {
        if (ret.intersectionRatio > 0) {
          list[i].show = true
        }
        this.setData({
          list
        })
 })
}

最后

我們使用三種方式完成了小程序的瀑布流布局,還額外完成了基于瀑布流的懶加載。可以發現使用css最簡便,雖然小程序不能操作DOM,但是我們改完數據其實和改變DOM一樣,將觀念轉變過來,小程序的開發還是很爽的。

最后的最后,各位,周末快樂。

github

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 問答題47 /72 常見瀏覽器兼容性問題與解決方案? 參考答案 (1)瀏覽器兼容問題一:不同瀏覽器的標簽默認的外補...
    _Yfling閱讀 13,786評論 1 92
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,833評論 25 708
  • 春天喚醒沉睡的大地 嫩綠的芽兒探出了頭 它睜開懵懂的眼睛 看見了一個美麗的姑娘 從它的枝條下走過 長長的頭發窈窕的...
    愛寶丫閱讀 294評論 6 6
  • 那年長街春意正濃也就一個轉身你醉眼迷夢跌入懷袖也就一個眼神注定癡纏一生 你曾是誰的夢夢醒過后注定不是彼此的世界后來...
    小橋君子閱讀 682評論 0 2
  • 理想今年你幾歲 你總是誘惑著年輕的朋友
    方圓日記閱讀 565評論 1 2