<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>触底加载</title>
<style>
* {
margin: 0;
padding: 0;
}
.content {
width: 1200px;
background: skyblue;
margin: 0 auto;
/* 让content下的div横向排列 */
display: flex;
/* 换行 */
flex-wrap: wrap;
/* 两端对齐 */
justify-content: space-between;
}
.content div {
width: 340px;
height: 300px;
background: hotpink;
margin-top: 50px;
font-size: 40px;
color: #fff;
text-align: center;
line-height: 300px;
}
</style>
</head>
<body>
<div class="content">
<!-- <div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div> -->
</div>
<script>
// 由于商品信息一般是动态获取的
//所以可以先遍历div插入content内部
window.onload = function () {
// 先获取元素,并且由于获取到的元素是数据形式所以要要后边加上数组下标
var content = document.getElementsByClassName("content")[0]
// 遍历content下面的9个div
for (var i = 0; i <= 9; i++) {
// 生成一个新的节点
var neWDiv = document.createElement("div")
// 把bgColor()的返回值赋给新节点,让新节点随机生成背景色
neWDiv.style.background = bgColor()
// 在新节点中依次插入i
neWDiv.innerHTML = i
// 这时注释html中content下的div,页面就什么都没有了
// 这时再用父节点content遍历出新节点
content.appendChild(neWDiv)
}
//触底加载功能
// 当滚动条滚动的时候触发以下函数
window.onscroll = function () {
// 先打印事件是否生效
console.log("我滚了");
// 获取鼠标向上滑动的内容滑动了多少
var ScrollTop = document.documentElement.scrollTop
// 获取设备的高度
var clientHeight = document.documentElement.clientHeight
// 获取body的高度,也就是页面内容的高度
var bodyHeight = document.body.clientHeight
// 判断滚动条什么时候到达底部:即内容高度-向上滚动距离的差等于设备高度的时候就是到达底部了
console.log(ScrollTop, clientHeight, bodyHeight);
if (parseInt(bodyHeight - ScrollTop) == clientHeight) {
console.log("触底了");
// 遍历content下面的9个div
for (var i = 0; i <= 9; i++) {
// 生成一个新的节点
var neWDiv = document.createElement("div")
// 把bgColor()的返回值赋给新节点,让新节点随机生成背景色
neWDiv.style.background = bgColor()
// 在新节点中依次插入i
neWDiv.innerHTML = i
// 这时注释html中content下的div,页面就什么都没有了
// 这时再用父节点content遍历出新节点
content.appendChild(neWDiv)
}
}
}
// 封装一个函数用于生成随机的背景色
function bgColor() {
//由于random的随机范围是0-1,而rgb的取值范围是0-255,所以要给random方法乘上255
//又由于rgb的取值范围是包括255和0的,为了能取到255,给random方法加一个四舍五入的方法
var r = Math.round(Math.random() * 255)
var g = Math.round(Math.random() * 255)
var b = Math.round(Math.random() * 255)
// 使用模板字符串把随机生成的rgb数字插进去
return `rgb(${r},${g},${b})`
}
}
</script>
</body>
</html>
【无标题】
最新推荐文章于 2025-06-13 08:24:12 发布