JavaScript滚动条或其他事件监听时卡顿问题解决

问题定位追踪(此问题用户scroll事件举例)

window.addEventListener(‘scroll’, func)
此时监听时会导致鼠标一滚动就会被监听,极大的影响了页面的性能。

解决方法

防抖(debounce):
个人理解防抖主要就是通过定时器来限制页面事件监听处理次数。

上代码(项目中使用的代码仅限参考)

代码主要是通过滚动监听来控制nav导航的悬浮。
// 防抖函数
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
var myEfficientFn = debounce(function() {
var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
var offsetTop = document.querySelector(’.hds_container’).offsetTop
if (scrollTop > 220) {
if (scrollTop > offsetTop) {
// true
if ($(’.m-header-fixed’).length != 0) {
$(".hds_container").removeClass(“isFixedNoTop”);
$(".hds_container").addClass(“isFixed”);
} else {
$(".hds_container").removeClass(“isFixed”);
$(".hds_container").addClass(“isFixedNoTop”);
}
} else {
// false
$(".hds_container").removeClass(“isFixed”);
$(".hds_container").removeClass(“isFixedNoTop”);
}
} else {
// false
$(".hds_container").removeClass(“isFixed”);
$(".hds_container").removeClass(“isFixedNoTop”);
}
}, 100);
window.addEventListener(‘scroll’,myEfficientFn);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值