目录
瀑布流
等宽瀑布流,使用定位,根据元素实际宽高,计算位置
公式:(100%-col*space) / col
获取元素坐标(y)
function offset_b(el) {
return $(el).height() + parseInt($(el).css("top"))
}
等比例公式
img_h = img_w * height / width
遍历添加元素
$(".note>li").each((index, li) => {
if (index < 3) {
const liLeft = index * (li_w + space)
$(li).css({ top: 0, left: liLeft })
result.push(li)
} else {
var min_li = result[0]
result.forEach(lis => {
if (offset_b(lis) < offset_b(min_li)) {
min_li = lis
}
})
// 新增加元素放在min_li元素正下方
$(li).css({
left: $(min_li).css("left"),
top: offset_b(min_li) + space,
})
// 将新增加的元素push进数组,然后删除min_li
result.push(li)
const i = result.indexOf(min_li)
result.splice(i, 1)
}
})
设置父元素高度,动态添加偏移量
let max_li = result[0]
result.forEach(lis => {
if (offset_b(lis) > offset_b(max_li)) {
max_li = lis
}
})
$(".note").css("height", offset_b(max_li))
index.js
$(function () {
// 当前页
let nowPage = 1
let flag = false
// 等宽瀑布流,使用定位,根据元素实际宽高,计算位置
// 公式:(100%-col*space) / col
const space = 20
const li_w = (1000 - 3 * space) / 3
let result = []
// 获取元素偏移量 (y)
function offset_b(el) {
return $(el).height() + parseInt($(el).css("top"))
}
// 等比例公式:img_h / img_w = height / width
// img_h = img_w * height / width
function getData(param) {
var url = `https://serverms.xin88.top/note?page=${param}`
flag = true
$.get(url, function (el) {
// 解锁
flag = false
// 更新当前页
nowPage = el.page
if (nowPage == el.pageCount) {
$(".loadmore").text("没有更多了").addClass("nomore")
}
$(".note").append(
el.data.map((value, index) => {
const { title, cover, height, width, head_icon, name, favorite } =
value
const img_h = (li_w * height) / width
return `
<li style="width: ${li_w}px">
<a href="">
<img style="height: ${img_h}px" src="./assets/img/note/${cover}" alt="" />
</a>
<div>
<a href="" class="line-2">${title}</a>
<div>
<a href="">
<img class='user-head' src="./assets/img/note/${head_icon}" alt="" />
</a>
<a href="">${name}</a>
<a href="">${favorite}</a>
</div>
</div>
</li>
`
})
)
result = []
// 遍历添加的每一个li元素
$(".note>li").each((index, li) => {
if (index < 3) {
const liLeft = index * (li_w + space)
$(li).css({ top: 0, left: liLeft })
result.push(li)
} else {
var min_li = result[0]
result.forEach(lis => {
if (offset_b(lis) < offset_b(min_li)) {
min_li = lis
}
})
// 新增加元素放在min_li元素正下方
$(li).css({
left: $(min_li).css("left"),
top: offset_b(min_li) + space,
})
// 将新增加的元素push进数组,然后删除min_li
result.push(li)
const i = result.indexOf(min_li)
result.splice(i, 1)
}
})
// 设置父元素高度,获取li中底部最高的,top
let max_li = result[0]
result.forEach(lis => {
if (offset_b(lis) > offset_b(max_li)) {
max_li = lis
}
})
$(".note").css("height", offset_b(max_li))
console.log(el)
})
}
getData(1)
getData(2)
// 加载更多,滚动监听
$(window).on("scroll", function () {
var win_h = $(window).height()
var st = $(window).scrollTop()
// 顶部偏移量
var top = $(".loadmore").offset().top
if (st > top - win_h && !flag && !$(".loadmore").hasClass("nomore")) {
console.log("请求更多……")
getData(nowPage + 1)
}
})
})