原生JS實現瀑布流外掛程式,js瀑布

來源:互聯網
上載者:User

原生JS實現瀑布流外掛程式,js瀑布

瀑布流布局中的圖片有一個核心特點—等寬不定等高,瀑布流布局在國內網網站都有一定規模的使用,比如pinterest、花瓣網等等。那麼接下來就基於這個特點開始瀑布流探索之旅。

基礎功能實現

首先我們定義好一個有 20 張圖片的容器,

<body> <style>  #waterfall {   position: relative;  }  .waterfall-box {   float: left;   width: 200px;  } </style></body><div id="waterfall">  <img src="images/1.png" class="waterfall-box">  <img src="images/2.png" class="waterfall-box">  <img src="images/3.png" class="waterfall-box">  <img src="images/4.png" class="waterfall-box">  <img src="images/5.png" class="waterfall-box">  <img src="images/6.png" class="waterfall-box">  ... </div>由於未知的 css 知識點,絲襪最長的妹子把下面的空間都佔用掉了。。。接著本文,假如如,每排有 5 列,那第 6 張圖片應該出現前 5 張圖片哪張的下面呢?當然是絕對位置到前 5 張圖片高度最小的圖片下方。那第 7 張圖片呢?這時候把第 6 張圖片和在它上面的圖片當作是一個整體後,思路和上述是一致的。代碼實現如下:Waterfall.prototype.init = function () { ... const perNum = this.getPerNum() // 擷取每排圖片數 const perList = []       // 儲存第一列的各圖片的高度 for (let i = 0; i < perNum; i++) {  perList.push(imgList[i].offsetHeight) } let pointer = this.getMinPointer(perList) // 求出當前最小高度的數組下標 for (let i = perNum; i < imgList.length; i++) {  imgList[i].style.position = 'absolute' // 核心語句  imgList[i].style.left = `${imgList[pointer].offsetLeft}px`  imgList[i].style.top = `${perList[pointer]}px`  perList[pointer] = perList[pointer] + imgList[i].offsetHeight // 數組最小的值加上相應圖片的高度  pointer = this.getMinPointer(perList) }}

細心的朋友也許發現了代碼中擷取圖片的高度用到了 offsetHeight 這個屬性,這個屬性的高度之和等於圖片高度 + 內邊距 + 邊框,正因為此,我們用了 padding 而不是 margin 來設定圖片與圖片之間的距離。此外除了offsetHeight 屬性,此外還要理解 offsetHeightclientHeightoffsetTopscrollTop 等屬性的區別,才能比較好的理解這個項目。css 代碼簡單如下:

.waterfall-box { float: left; width: 200px; padding-left: 10px; padding-bottom: 10px;}
scroll、resize 事件監聽的實現

實現了初始化函數 init 以後,下一步就要實現對 scroll 滾動事件進行監聽,從而實現當滾到父節點的底部有源源不斷的圖片被載入出來的效果。這時候要考慮一個點,是滾動到什麼位置時觸發載入函數呢?這個因人而異,我的做法是當滿足 父容器高度 + 滾動距離 > 最後一張圖片的 offsetTop 這個條件,即橙色線條 + 紫色線條 > 藍色線條時觸發載入函數,代碼如下:

window.onscroll = function() { // ... if (scrollPX + bsHeight > imgList[imgList.length - 1].offsetTop) {// 瀏覽器高度 + 滾動距離 > 最後一張圖片的 offsetTop  const fragment = document.createDocumentFragment()  for(let i = 0; i < 20; i++) {   const img = document.createElement('img')   img.setAttribute('src', `images/${i+1}.png`)   img.setAttribute('class', 'waterfall-box')   fragment.appendChild(img)  }  $waterfall.appendChild(fragment) }}

因為父節點可能自訂節點,所以提供了對監聽 scroll 函數的封裝,代碼如下:

proto.bind = function () {  const bindScrollElem = document.getElementById(this.opts.scrollElem)  util.addEventListener(bindScrollElem || window, 'scroll', scroll.bind(this)) } const util = {  addEventListener: function (elem, evName, func) {   elem.addEventListener(evName, func, false)  }, }

resize 事件的監聽與 scroll 事件監聽大同小異,當觸發了 resize 函數,調用 init 函數進行重設就行。

使用發布-訂閱模式和繼承實現監聽綁定

既然以開發外掛程式為目標,不能僅僅滿足於功能的實現,還要留出相應的操作空間給開發人員自行處理。聯想到業務情境中瀑布流中下拉載入的圖片一般都來自 Ajax 非同步擷取,那麼載入的資料必然不能寫死在庫裡,期望能實現如下調用(此處借鑒了 waterfall 的使用方式),

const waterfall = new Waterfall({options})waterfall.on("load", function () { // 此處進行 ajax 同步/非同步添加圖片})

觀察調用方式,不難聯想到使用發布/訂閱模式來實現它,關於發布/訂閱模式,之前在 Node.js 非同步異聞錄 有介紹它。其核心思想即通過訂閱函數將函數添加到緩衝中,然後通過發布函數實現非同步呼叫,下面給出其代碼實現:

function eventEmitter() { this.sub = {}}eventEmitter.prototype.on = function (eventName, func) { // 訂閱函數 if (!this.sub[eventName]) {  this.sub[eventName] = [] } this.sub[eventName].push(func) // 添加事件監聽器}eventEmitter.prototype.emit = function (eventName) { // 發布函數 const argsList = Array.prototype.slice.call(arguments, 1) for (let i = 0, length = this.sub[eventName].length; i < length; i++) {  this.sub[eventName][i].apply(this, argsList) // 呼叫事件監聽器 }}

接著,要讓 Waterfall 能使用發布/訂閱模式,只需讓 Waterfall 繼承 eventEmitter 函數,代碼實現如下:

function Waterfall(options = {}) { eventEmitter.call(this) this.init(options) // 這個 this 是 new 的時候,綁上去的}Waterfall.prototype = Object.create(eventEmitter.prototype)Waterfall.prototype.constructor = Waterfall
繼承方式的寫法吸收了基於建構函式繼承和基於原型鏈繼承兩種寫法的優點,以及使用 Object.create 隔離了子類和父類,關於繼承更多方面的細節,可以另寫一篇文章了,此處點到為止。

小最佳化

為了防止 scroll 事件觸發多次載入圖片,可以考慮用函數防抖與節流實現。在基於發布-訂閱模式的基礎上,定義了個 isLoading 參數表示是否在載入中,並根據其布爾值決定是否載入,代碼如下:

let isLoading = falseconst scroll = function () { if (isLoading) return false // 避免一次觸發事件多次 if (scrollPX + bsHeight > imgList[imgList.length - 1].offsetTop) { // 瀏覽器高度 + 滾動距離 > 最後一張圖片的 offsetTop  isLoading = true  this.emit('load') }}proto.done = function () { this.on('done', function () {  isLoading = false  ... }) this.emit('done')}
這時候需要在調用的地方加上 waterfall.done, 從而告知當前圖片已經載入完畢,代碼如下:
const waterfall = new Waterfall({})waterfall.on("load", function () { // 非同步/同步載入圖片 waterfall.done()})
源碼地址:https://github.com/MuYunyun/waterfall

項目簡陋,不足之處在所難免,歡迎留下你們寶貴的意見。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.