老师,我的代码在第二种情况下好像有点问题,麻烦老师帮我看一看
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
<meta name='viewport'
content='width=device-width, initial-scale=1.0,user-scalable=no,maximum-scale=1.0,minimum-scale=1.0'>
<title>Document</title>
<style>
html {
height: 2000px;
}
.none {
display: none;
}
div {
width: 100px;
height: 100px;
background-color: red;
}
</style>
<script src='https://unpkg.com/vue@next'></script>
</head>
<body>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<button id="backTop" class="none">回到顶部</button>
<script>
const $bakcTop = document.getElementById('backTop');
//当window大小变化时重新获取;
let WH = window.innerHeight;
window.addEventListener('resize', () => {
WH = window.innerHeight;
//console.log(`innerHeight${window.innerHeight}`);
}, false);
window.addEventListener('scroll',
//节流
throttle(handler), false);
function handler() {
//console.log(document.documentElement.scrollTop);
if (document.documentElement.scrollTop >= WH) {
$bakcTop.classList.remove('none');
} else {
$bakcTop.classList.add('none');
}
console.log('scroll');
}
//节流函数:事件处理函数执行一次后,在某个时间期限内不再工作;
function throttle(fn, miliseconds = 250, context) {
//上一次事件触发的时间戳
console.log(1);
let lastEventTimestamp = null;
return function (...args) {
const self = context || this;
const now = Date.now();
// console.log(args);
if (!lastEventTimestamp || now - lastEventTimestamp >= miliseconds) {
lastEventTimestamp = now;
//在某个期限过后,才能执行下次的处理函数
fn.apply(self, args);
}
};
}
</script>
</body>
</html>
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星