1. 程式人生 > 程式設計 >jQuery實現動態載入瀑布流

jQuery實現動態載入瀑布流

jquery實現瀑布流,供大家參考,具體內容如下

案例分析

  • 首先,它的每個圖片是等寬的
  • 其次,除第一排正常顯示其餘的圖片都會顯示在上一排中高度最小的那個圖片的下面
  • 最後,就是根據最矮圖片所在位置的寬高來,決定絕對定位設定圖片顯示的位置

效果圖

jQuery實現動態載入瀑布流

實現步驟

html結構

<div class="container">
 <div class="box">
 <div class="content"><img src="./image/1.jpg" alt="jQuery實現動態載入瀑布流"></div>
 </div>
 <div class="box">
 <div class="content"><img src="./image/2.jpg" alt="jQuery實現動態載入瀑布流"></div>
 </div>
 <div class="box">
 <div class="content"><img src="./image/3.jpg" alt="jQuery實現動態載入瀑布流"></div>
 </div>

 </div>
</div>

css樣式

具體就是對每個boxdiv浮動並設定樣式

* {
 padding: 0;
 margin: 0;
 }

 .box {
 position: relative;
 float: left;
 margin: 10px;
 }

 .content {
 padding: 15px;
 border: 1px solid #ccc;
 box-shadow: 0 0 5px #ccc;
 border-radius: 10px;
 }

 .content img {
 width: 200px;
 height: auto;
 }

js(jquery)程式碼

主要是根據一排中高度最小的寬度個高度進行絕對定位的設定

<script>
 $(function () {
 //jQuery程式碼
 imgLocation()
 
 function imgLocation() {
 var box = $('.box')
 var num = Math.floor($(window).width() / box.eq(0).width())
 var boxHeights = []
 box.each(function (index,value) {
 var boxHeight = box.eq(index).height()
 if (index < num) {
 boxHeights[index] = boxHeight
 } else {
 var minHeight = Math.min.apply(null,boxHeights)
 var minIndex = $.inArray(minHeight,boxHeights)
 $(value).css({
 'position': 'absolute','top': minHeight,'left': box.eq(minIndex).position().left
 });
 boxHeights[minIndex] += box.eq(index).height()
 }
 })
 }
 })
</script>

根據滑鼠的滾動動態的載入圖片

案例分析

這裡的動態是主要是模仿動態載入資料(偽動態)

  • 首先,根據滑鼠滾動的大小和介面的高度判斷是否要動態載入
  • 其次,就是訪問資料,並動態形成jquery資料型別
  • 最後,把生成的資料追加的.container中進行顯示

效果圖

jQuery實現動態載入瀑布流

實現步驟

  • htmlcss的程式碼都一樣這裡就不重複寫了
  • js程式碼

主要是判斷什麼時候新增圖片資料,新增後插入到模板就行了

其中的dataImg就是模仿的假資料

var dataImg = { 'data': [{ 'src': '1.jpg' },{ 'src': '2.jpg' },{ 'src': '3.jpg' },{ 'src': '4.jpg' }] }
 window.onscroll = function () {
 if (scrollside()) {
 $.each(dataImg.data,function (index,value) {
 var html = `<div class="box">
 <div class="content"><img src="./image/${value.src}" alt="jQuery實現動態載入瀑布流"></div>
 </div>`
 $(html).appendTo($('.container'))
 })
 imgLocation()
 }
 }
 function scrollside() {
 var box = $('.box')
 var lastboxHeight = box.last().get(0).offsetTop
 var documentHeight = document.body.scrollHeight + 130
 var scrollHeight = $(document).scrollTop()
 console.log(lastboxHeight,scrollHeight,documentHeight)
 return (lastboxHeight < scrollHeight + documentHeight) ? true : false
 }


oxHeight,documentHeight)
 return (lastboxHeight < scrollHeight + documentHeight) ? true : false
 }

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。