瀑布流
<style>
body {
margin: 0;
}
.list {
list-style: none;
margin: 0;
padding: 0;
}
.list>li {
float: left;
font-size: 0;
}
.list>li>img {
width: 100%;
}
</style>
<script type="module">
import { createDom } from "./js/createDom.js";
const COL = 5;
var list = Array(COL).fill(0), n = 2;
var ul;
init();
function init() {
ul = createDom("ul", { className: "list" });
ul.innerHTML = Array.from({ length: COL }).reduce((v, t) => v + `<li style="width:${100 / COL}%"></li>`, "");
document.body.appendChild(ul)
loadImage(`./img/${n}-.jpg`)
}
function loadImage(src) {
var img = new Image();
img.src = src;
img.addEventListener("load", loadHandler, { once: true });
}
function loadHandler(e) {
var min = Math.min(...list);
var index = list.indexOf(min);
ul.children[index].appendChild(this);
list[index] += ul.children[index].offsetHeight;
n++;
if (n > 79) return;
loadImage(`./img/${n}-.jpg`);
}
</script>
懒加载
<style>
body {
margin: 0;
}
.list {
list-style: none;
margin: 0;
padding: 0;
}
.list>li {
float: left;
font-size: 0;
}
.list>li>img {
width: 100%;
}
</style>
<script type="module">
import { createDom } from "./js/createDom.js";
const COL = 5;
var list = Array(COL).fill(0), n = 2;
var ul;
init();
function init() {
ul = createDom("ul", { className: "list" });
ul.innerHTML = Array.from({ length: COL }).reduce((v, t) => v + `<li style="width:${100 / COL}%"></li>`, "");
document.body.appendChild(ul);
loadImage(`./img/${n}-.jpg`);
document.addEventListener("scroll", scrollHandler);
}
function loadImage(src) {
var img = new Image();
img.src = src;
img.addEventListener("load", loadHandler, { once: true });
}
function loadHandler(e) {
var min = Math.min(...list);
var index = list.indexOf(min);
ul.children[index].appendChild(this);
list[index] += ul.children[index].offsetHeight;
if ((document.body.scrollHeight - document.documentElement.scrollTop) / document.documentElement.clientHeight > 4) return;
continueLoadImg();
}
function scrollHandler(e) {
if ((document.body.scrollHeight - document.documentElement.scrollTop) / document.documentElement.clientHeight < 2) {
continueLoadImg();
}
}
function continueLoadImg() {
n++;
if (n > 79) {
n = 2;
}
loadImage(`./img/${n}-.jpg`)
}
</script>