Javascript实现瀑布流
- 下面是瀑布流的js实现过程,前提条件,后端返回的图片信息需携带图片的width和height,用于js计算图片位置,否则无法实现瀑布流,效果可以参考 Pngink
- 有点小依赖jquery,有能力将dom操作部分替换为原生的即可。
<div class="maindom">
<div width="100" height="221" class="imgdom">
<div>
<img src="" class="imgli-img" alt=""/>
</div>
<div class="info imgli-img-title" style="height: 25px">
<a href="/preview/`在这里插入代码片`" title="{$v.title}">标题</a>
</div>
</div>
</div>
let def_width =200;
let def_margin = 15;
let h_arr = [];
let clounm = 0;
let imgdom = null;
let maindom = null;
function init(main = false, imgs = false) {
if (main != false) {
maindom = main
}
if (imgs != false) {
imgdom = imgs
}
let window_width = $(maindom).width();
if (window_width < 600) {
def_width = 180
}
if (window_width < 400) {
def_width = 130
}
h_arr = [];
clounm = Math.floor((window_width + def_margin) / (def_width + def_margin));
def_width = Math.floor(((window_width + def_margin) / clounm) - def_margin);
for (i = 0; i < clounm; i++) {
h_arr.push(0)
}
render()
}
function min(arr) {
const num = Math.min(...h_arr);
const index = h_arr.indexOf(num)
return index;
}
function sum_left(index = 0) {
return index * def_width + (index * def_margin);
}
function sum_height(w, h) {
const rota = w / def_width;
return parseInt(h / Math.abs(rota));
}
function render() {
const list = $(imgdom);
for (const listElement of list) {
let img = $(listElement);
let index = min(h_arr);
const left = sum_left(index);
let height = parseInt(sum_height(img.attr('width'), img.attr('height')));
img.css({
position: 'absolute',
width: def_width,
height: height,
opacity: 1,
transform: `translateX(${left}px) translateY(${h_arr[index]}px)`,
})
let size = height + 15;
if ($(img).find(".info").text() != "") {
size += $(img).height();
}
h_arr[index] += size
$(maindom).css({
height: Math.max(...h_arr), opacity: 1
})
}
}
function debounce(fn, wait) {
var timer = null;
return function () {
if (timer !== null) {
clearTimeout(timer);
}
timer = setTimeout(fn, wait);
}
}
init("maindom","imgdom");
window.addEventListener("resize", debounce(init, 100));