参考博客:
引言
监听浏览器滚动事件,打印 当前滚条到顶部的距离,但函数执行的频率太高!
- 防抖和节流 来实现 性能优化
代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>防抖/节流=>来显示滚动条到顶端的距离</title>
<style type="text/css">
#box {
height: 2000px;
border: 2px solid red;
}
.btn {
width: 40px;
height: 40px;
position: fixed;
right: 70px;
bottom: 70px;
}
</style>
</head>
<body>
<div id="box">
</div>
<button class="btn" type="button" onclick="toTop()">TOP</button>
</body>
<script type="text/javascript">
// 显示滚动条到顶端的距离/点击按钮回到top
function toTop() {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
}
// function showTop(){
// var scrollTop = Math.floor(document.body.scrollTop || document.documentElement.scrollTop);
// console.log('滚动条位置:' + scrollTop);
// }
// window.onscroll = showTop
// 《《《《《《《《《《《《《《《=====防抖=====实现显示滚动条到顶端的距离》》》》》》》》》》》》》》》》》》》》》》
// 一版防抖函数
/*
* fn [function] 需要防抖的函数
* delay = 1000 [number] 毫秒,防抖期限值
*/
// function debounce(fn,delay){
// let timer = null //借助闭包
// return function() {
// if(timer){
// clearTimeout(timer) //进入该分支语句,说明当前正在一个计时过程中,并且又触发了相同事件。所以要取消当前的计时,重新开始计时
// timer = setTimeout(fn,delay)
// }else{
// timer = setTimeout(fn,delay) // 进入该分支说明当前并没有在计时,那么就开始一个计时
// }
// }
// }
// function showTop(){
// var scrollTop = Math.floor(document.body.scrollTop || document.documentElement.scrollTop);
// console.log('滚动条位置:' + scrollTop);
// }
// window.onscroll = debounce(showTop,600);
/*****************************简化后的分割线 ******************************/
// function debounce(fn,delay){
// let timer = null //借助闭包
// return function() {
// if(timer){
// clearTimeout(timer)
// }
// timer = setTimeout(fn,delay) // 简化写法
// }
// }
// // 然后是旧代码
// function showTop () {
// var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
// console.log('滚动条位置:' + scrollTop);
// }
// window.onscroll = debounce(showTop,500) // 为了方便观察效果我们取个大点的间断值,实际使用根据需要来配置
// function debounce(fn,delay){
// let timer = null;
// return function(){
// if(timer){
// clearTimeout(timer)
// }
// timer = setTimeout(fn,delay);
// }
// }
// function showTop() {
// var scrollTop = Math.floor(document.body.scrollTop || document.documentElement.scrollTop);
// console.log('距top位置:' + scrollTop);
// }
// window.onscroll = debounce(showTop,500)
// 《《《《《《《《《《《《《《《=====节流=====实现显示滚动条到顶端的距离》》》》》》》》》》》》》》》》》》》》》》
function throttle(fn,delay){
let valid = true
return function() {
if(!valid){
//休息时间 暂不接客
return false
}
// 工作时间,执行函数并且在间隔期内把状态位设为无效
valid = false
setTimeout(() => {
fn()
valid = true;
}, delay)
}
}
/* 请注意,节流函数并不止上面这种实现方案,
例如可以完全不借助setTimeout,可以把状态位换成时间戳,然后利用时间戳差值是否大于指定间隔时间来做判定。
也可以直接将setTimeout的返回的标记当做判断条件-判断当前定时器是否存在,如果存在表示还在冷却,并且在执行fn之后消除定时器表示激活,原理都一样
*/
// 以下照旧
function showTop () {
var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
console.log('滚动条位置:' + scrollTop);
}
window.onscroll = throttle(showTop,300)
</script>
</html>