防抖和节流严格算起来应该属于性能优化的知识,但实际上遇到的频率相当高, 处理不当或者放任不管就容易引起浏览器卡死。所以还是很有必要早点掌握的。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body{
height: 2000px;
background-color: aqua;
}
</style>
<title>Document</title>
</head>
<body>
<!-- 防抖和节流严格算起来应该属于性能优化的知识,但实际上遇到的频率相当高,
处理不当或者放任不管就容易引起浏览器卡死。所以还是很有必要早点掌握的。 -->
<!-- 返回顶部按钮 这个按钮只会在滚动到距离顶部一定位置之后才出现,那么我们现在提取出这个功能需求--
监听浏览器滚动事件,返回当前滚条与顶部的距离 -->
</body>
</html>
<script>
function debounce(showTop,delay){
let timer = null
return function() {
if(timer){
clearTimeout(timer)
}
timer = setTimeout(showTop,delay)
}
}
function showTop () {
var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
console.log('滚动条位置:' + scrollTop);
}
window.onscroll = debounce(showTop,1000)
</script>