1.新建一个空盒子
<div class="box"></div>
2.书写样式
<style>
* {
margin: 0;
padding: 0;
}
.box {
position: relative;
margin: 0 auto;
width: 1100px;
height: 200px;
border: 1px solid #000;
}
.list {
position: absolute;
width: 100px;
height: auto;
margin: 5px 0;
opacity: 0;
transition: opacity .3s linear;
}
</style>``
3.导入js代码
<script src="js/Pinterest.js"></script>
/*
加载图片的远程路径
*/
var str = [
"https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2584783080,814052527&fm=26&gp=0.jpg",
"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1594201391277&di=7d4959577f3fcb736a85d272f119c2ac&imgtype=0&src=http%3A%2F%2Fbos.pgzs.com%2Frbpiczy%2FWallpaper%2F200908%2F06%2F27%2F337dc87ec83503fada74a7a38459aa28.jpg",
"https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=2832305377,1681809629&fm=26&gp=0.jpg",
"https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=1020264113,2955297144&fm=26&gp=0.jpg",
"https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=2384200885,2252030111&fm=11&gp=0.jpg"
];
//使用动态获取
var list = document.getElementsByClassName("list");
//获取界面的box元素
var box = document.querySelector(".box");
var srcIndex = 0;//获取图片路径随机值
var imageCount = 40;//默认加载10张
var count = 0;
var showH = 10; //一行显示10张
var maxHeight = 0;//记录box盒子最大高
CreateImage();
/*
* 给页面生成图片的
* */
function CreateImage() {
var BeforeImage = new Image();
BeforeImage.className = "list";
//设置索引随机值
srcIndex = parseInt(Math.random() * str.length);
BeforeImage.src = str[0];
BeforeImage.onload = function () {
var that = this;
//可以显示界面
box.appendChild(this);
setTimeout(function () {
setImageStyle(that);
if (count >= imageCount - 1) {
return;
}
count++;
//这里实现延迟加载
CreateImage();
}, 10);
}
BeforeImage.onerror = function () {
//图片加载失败
this.alt = "图片加载失败";
}
BeforeImage = null;
}
/*
* 设置image对象的相关样式
* */
function setImageStyle(obj) {
obj.style.opacity = 1;
obj.style.left = (count % showH * 110) + "px";
//获取上一个元素实际高
var top = 0;
if (count < showH) {
top = 0;
}
else {
console.log(list);
top = list[count - showH].offsetHeight + list[count - showH].offsetTop;
}
obj.style.top = top + "px";
var offset = obj.offsetHeight + top;
if (offset >= maxHeight) {
maxHeight = offset;
}
//动态计算 box盒子最大高
box.style.height = maxHeight + 10 + "px";
}
/*
* 滚动条事件
* */
window.onscroll = function () {
/*
* this.scrollY 滑动高 32
* document.documentElement.clientHeight 705
* document.body.clientHeight body 的高 737
* */
var htmlH = document.documentElement.clientHeight;
var bodyH = document.body.clientHeight;
if (this.scrollY + htmlH >= bodyH) {
imageCount += 20;
count++;
CreateImage();
}
}