瀑布流+懶加載+函數(shù)節(jié)流

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    .container {
      position: relative;
      width: 100%;
      margin: 0 auto;
    }

    img {
      width: 100px;
      position: absolute;
      margin: 5px 5px;
      opacity: 0.5;
      transition: all 0.5s;
    }

    .loading {
      position: relative;
      z-index: 2;
      width: 100vw;
      height: 100vh;
      background-image: url(http://smashinghub.com/wp-content/uploads/2014/08/cool-loading-animated-gif-3.gif);
      background-size: cover;
      background-repeat: no-repeat;

    }
  </style>
</head>

<body>
  <div class="container">
    <img src="http://via.placeholder.com/100x100" alt="圖片">
  </div>
  <div class="loading">
  </div>
  <script src="https://code.jquery.com/jquery-3.1.0.js"></script>
  <script>
    //瀑布流渲染
    var waterfall = {
      init: function () {
        this.isloading = true
        this.bind()
      },
      //初始化數(shù)據(jù)
      dataInit: function () {
        this.imgNumber = null //img有多少個(gè)
        this.heightArray = []
        this.imgWidth = $('.container img').outerWidth(true)
        this.minHeight = null
        this.minIndex = null
        this.imgNumber = Math.floor($('.container').width() / this.imgWidth)
        for (let i = 0; i < this.imgNumber; i++) {
          this.heightArray[i] = 0 //初始化高度數(shù)組都是0這樣第一行所有圖片都會(huì)在頂部
        }
        this.lineNumber = Math.floor($(window).height() / $('.container img').outerHeight(true)) //計(jì)算有多少行
      },
      bind: function () {
        let _this = this
        // 先初始化數(shù)據(jù)
        this.dataInit()
        // 根據(jù)用戶瀏覽器大小插入相應(yīng)數(shù)量的img
        this.imgTemplate(this.imgNumber, this.lineNumber)
        // 對(duì)加載完的img進(jìn)行瀑布流布局
        this.imgLoad()
        // 判斷img加載完成Hide windowLoading
        this.loadingTimer = setInterval(function () {
          _this.winLoad()
        }, 1000)
      },
      //瀑布流核心代碼,思路是load會(huì)為加載完成圖片處理
      imgLoad: function () {
        var _this = this
        $('img').on('load', function () {
          _this.minHeight = _this.heightArray[0]
          _this.minIndex = 0
          for (let i = 0; i < _this.imgNumber; i++) {
            if (_this.heightArray[i] < _this.minHeight) {
              _this.minHeight = _this.heightArray[i]
              _this.minIndex = i
            }
          }
          $(this).css({
            left: _this.minIndex * _this.imgWidth,
            top: _this.minHeight,
            opacity: 1
          })
          _this.heightArray[_this.minIndex] += $(this).outerHeight(true)
        })
      },
      //值得注意的是需要將當(dāng)前所有img遍歷改變布局,相關(guān)數(shù)據(jù)需要初始化
      imgResize: function () {
        var _this = this
        $(window).on('resize', function () {
          _this.dataInit()
          $('img').each(function () {
            _this.minHeight = _this.heightArray[0]
            _this.minIndex = 0
            for (let i = 0; i < _this.imgNumber; i++) {
              if (_this.heightArray[i] < _this.minHeight) {
                _this.minHeight = _this.heightArray[i]
                _this.minIndex = i
              }
            }
            $(this).css({
              left: _this.minIndex * _this.imgWidth,
              top: _this.minHeight,
              opacity: 1
            })
            _this.heightArray[_this.minIndex] += $(this).outerHeight(true)
            // console.log(_this.heightArray)
          })
        })
      },
      //img模版
      imgTemplate: function (imgNumber, lineNumber) {
        this.sumNumber = imgNumber * lineNumber
        for (let i = 0; i < this.sumNumber; i++) {
          let $img = $('<img>')
          let $color = Math.floor(Math.random() * 256)
          let $imgSize = Math.floor(Math.random() * 300)
          $img.attr({
            src: `http://via.placeholder.com/100x${$imgSize}/${$color}`,
            alt: '圖片'
          })
          $('.container').append($img)
          console.log('append')
        }

      },
      // 懶加載+函數(shù)節(jié)流
      imgScroll: function () {
        let _this = this
        let timer = null
        $(window).on('scroll', function () {
          if (timer) {
            clearTimeout(timer)
          }
          timer = setTimeout(function () {
            let imgNumber = _this.imgNumber
            let lineNumber = _this.lineNumber
            if (_this.hasLoad($('img').last())) {
              console.log(1)
              _this.imgTemplate(imgNumber / 2, lineNumber / 2)
              _this.imgLoad()
              _this.loadingTimer = setInterval(function () {
                _this.winLoad()
              }, 1000)
            }
          }, 800)

        })
      },
      // 懶加載核心代碼
      hasLoad: function ($node) {
        let $winHeight = $(window).height()
        let $scrollTop = $(window).scrollTop()
        let $nodeHeight = $node.outerHeight(true)
        let $offset = $node.offset().top
        if ($winHeight + $scrollTop >= $offset - $nodeHeight) {
          return true
        } else {
          return false
        }
      },
      // 由于前邊會(huì)setInterval,需要每次進(jìn)入先off(load)
      winLoad: function () {
        let _this = this
        $(window).off('load')
        $(window).on('load', function () {
          _this.isloading = false
          // 當(dāng)視口加載完成后 清除setInterval
          clearInterval(_this.loadingTimer)
          // 添加scroll事件
          _this.imgScroll()
          // 添加resize事件
          _this.imgResize()
          $('.loading').hide()
        })
        console.log(_this.isloading, 'isloading')
      }
    }
    waterfall.init()
  </script>
</body>

</html>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容