不依賴任何框架,H5首頁瀑布流實現竟如此簡單!
阿新 • • 發佈:2021-01-21
技術標籤:前端javascriptcsshtml5
注意:此文章為純JS實現效果不依賴任何框架
為實現如下H5瀑布流顯示效果
html:
<div class="productcontent" style="padding-bottom: 70px;">
<div onclick="window.location='productdetails.html'" class="item" >
<div class="item-img" >
<img src="img/productdetail1.jpg" >
</div>
<div class="item-content">
小餅乾特賣啦超級好吃快...
</div>
<div class="item-tag">
<li>急速退款</li>
<li>假一罰三</li>
</ div>
<div class="item-price">
¥ 1999
</div>
</div>
</div>
css:
.productcontent{
padding-bottom: 70px;
width: 100%;
position:relative;
}
.item-content{
display : flex;
flex-direction: column;
justify-content: center;
padding: 5px;
height: 14px;
font-size: 14px;
font-weight: 400;
box-sizing: border-box;
margin-top: 5px;
}
.item-img img{
width:100%;
}
.item {
position: absolute;
width: calc(50% - 8px);
margin-left: 12px;
border: none;
background-color: white;
}
.item-tag{
padding: 5px;
color: #686868;
font-size: 12px;
}
.item-tag li{
float: left;
list-style: none;
margin-right: 10px;
}
.item-price{
color: #db4f47;
margin-top: 15px;
margin-left: 5px;
font-size: 16px;
}
js:
function waterFall() {
// 1 確定圖片的寬度 - 滾動條寬度
var pageWidth = getClient().width;
var columns = 2; //2列
var itemWidth = parseInt(pageWidth/columns)-16; //得到item的寬度
$(".item").width(itemWidth); //設定到item的寬度
var arr = [];
$(".productcontent .item").each(function(i){
var height = $(this).find("img").height();
if (i < columns) {
// 2 第一行按序佈局
$(this).css({
top:0,
left:(itemWidth) * i+8*i,
});
//將行高push到陣列
arr.push(height);
} else {
// 其他行
// 3 找到陣列中最小高度 和 它的索引
var minHeight = arr[0];
var index = 0;
for (var j = 0; j < arr.length; j++) {
if (minHeight > arr[j]) {
minHeight = arr[j];
index = j;
}
}
// 4 設定下一行的第一個盒子位置
// top值就是最小列的高度
$(this).css({
top:arr[index]+72,//設定30的距離
left:$(".productcontent .item").eq(index).css("left")
});
// 5 修改最小列的高度
// 最小列的高度 = 當前自己的高度 + 拼接過來的高度
arr[index] = arr[index] + height+72;//設定30的距離
}
});
}
//clientWidth 處理相容性
function getClient() {
return {
width: window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,
height: window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
}
}
// 頁面尺寸改變時實時觸發
window.onresize = function() {
//重新定義瀑布流
waterFall();
};
//初始化
window.onload = function(){
//實現瀑布流
waterFall();
}