<!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,maximum-scale=1.0, user-scalable=0">
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
}
body {
border: 1px solid #fff
}
#doc {
width: 200px;
height: 687px;
padding: 30px;
margin-top: 200px;
border: 10px solid #ccc;
}
</style>
</head>
<body>
<div id="doc">
<button onclick="debounceFn()">防抖点击</button>
<button onclick="throttleFn()">节流点击</button>
</div>
<script>
// 浏览器/浏览器屏幕 的 窗口高度 (不包含滚动条)
const clientHeight = document.documentElement.clientHeight;
// 滚动事件
window.addEventListener('scroll', debounce(scrollFn, 800))
function scrollFn () {
console.log('==========================================================');
console.log('浏览器/浏览器屏幕 的 窗口高度 (不包含滚动条)clientHeight:', clientHeight);
console.log('==========================================================');
// 获取DOM元素距离顶部的距离 ===》即文档高度(元素本身高度 + padding + border)
const docHeight = document.getElementById('doc').offsetHeight
/*
docHeight = 元素高度 + padding-top + paddingt-bottom + border-top + border-bottom
*/
console.log('元素高度docHeight,即文档高度(元素本身高度 + padding + border,[不包括margin])docHeight:', docHeight);
console.log('==========================================================');
//被卷去的距离,滚动后被隐藏的高度,也可以看作页面向上滑动了多少高度,margin+padding+border也都算在整体高度里
const scrollTop = document.documentElement.scrollTop
console.log('被卷去的距离,滚动后被隐藏的高度scrollTop:', scrollTop);
console.log('==========================================================');
const bodyScrollHeight = document.body.scrollHeight;
// 687 + 200 + 30 *2 + 10 *2 = 967
/*
document.documentElement.scrollHeight
*/
console.log('bodyScrollHeight is', bodyScrollHeight);
console.log('==========================================================');
console.log(`clientHeight + scrollTop = ${clientHeight + scrollTop} ====== ${bodyScrollHeight}`);
console.log('==========================================================');
if (clientHeight + scrollTop >= bodyScrollHeight) {
console.log('可以加载更多了');
}
// return () => window.removeEventListener('scroll', scrollFn)
}
// ------------防抖--------------------------------
// const debounceFn = debounce(print, 2000)
function debounce (callback, delay = 3000) {
let timer = null
return function () {
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
callback()
}, delay);
}
}
function print () {
console.log(123);
}
//------------节流(eg:2000内无论点击了多少次,都只执行第一次)--------------------------------
const throttleFn = throttle(print, 2000)
function throttle (callback, delay = 2000) {
let timer = null
return function () {
if (timer) return
callback()
timer = setTimeout(() => {
timer = null
}, delay);
}
}
</script>
</body>
</html>
js实现底部加载更多思路
最新推荐文章于 2024-04-17 10:05:48 发布