1. 程式人生 > >瀑布流布局(2)

瀑布流布局(2)

elements log client 動漫 ava off 數據 是否 app

前言

完成一個動漫人物的瀑布流布局,分別通過原生JavaScript、Css3和Jquery方式實現。
首先是使用JavaScript,這是第2部分。

一、檢測是否滿足 數據塊加載的條件

1 創建判斷函數

function checkScrollSlide(){
  var Boxs = document.getElementsByClassName(‘wrap‘);
  var lastBox= Boxs[Boxs.length-1]; //獲取最後一張圖片的 div塊
  // console.log(lastBox);  調試
  
  //最後一張圖片 距頁面頂部的高度+1/2圖片高
  var lastBoxHeight = lastBox.offsetTop + Math.floor(lastBox.offsetHeight/2) 
  //頁面已滾動高度+可視區 
  var scrolltop = document.documentElement.scrollTop || document.body.scrollTop;
  var cliHeight = document.documentElement.clientHeight || document.body.clientHeight;
  //判斷大小,當小於時返回true加載數據塊
  return lastBoxHeight<(scrolltop + cliHeight);
}

二、模擬獲取後臺數據

dataget = {"data":[{"src":‘img/1.jpg‘},{"src":‘img/2.jpg‘},{"src":‘img/3.jpg‘},{"src":‘4.jpg‘}]};

三、把數據塊渲染到頁面尾部,並正確定位

1 渲染數據塊

window.onscroll=function(){
    if (checkScrollSlide()){  //S1 判斷滿足什麽條件,才觸發加載事件—見下
      //S3 把數據塊渲染到頁面尾部
      var oneparent = document.querySelector(‘main‘);
      for (var i=0; i<dataIn.data.length; i++){
        var crbox = document.createElement(‘div‘);
        crbox.className = ‘wrap‘;   //創建元素的類名;
        oneparent.appendChild(crbox); //把 wrap盒子 添加到 main下面

        var crpic = document.createElement(‘div‘);
        crpic.className = ‘pic‘;
        crbox.appendChild(crpic);  //把 pic盒子 添加到 wrap下面

        var crimg = document.createElement(‘img‘);
        crimg.src = "img/" + dataIn.data[i].src; //創建圖片src屬性值
        crpic.appendChild(crimg);
      }
    }
  }

2 正確放置後加載的 圖片位置

waterfall("main",".wrap");

四 Reference

??1 Element.lastElementChild;

瀑布流布局(2)