我将多个事件绑定(bind)到滚动事件,并且当我尝试使用 window.location.hash = "hash"; 更新哈希时遇到性能问题。 。屏幕闪烁,页面随机跳转。 如何优化这段代码以提高性能并防止页面闪烁和跳跃?
我正在使用下面自定义编写的 jQuery 滚动事件,当您滚动一定距离时,该事件会更新页面的各个部分(我为每个部分创建了变量,这些变量是使用 .outerHeight 的部分)。所有内容都包含在 $(window).on('load resize', function(){} 中,以确保在计算高度之前窗口已完全加载。
自定义编写的jquery代码如下:
$(window).on('load resize', function(){
$(window).on('scroll', function(e){
var scrollLength = $(window).scrollTop();
var opacity = 0;
if( scrollLength <= fadeStart ){
opacity = 1;
}
if (scrollLength <= fadeUntil ){
opacity = 1- scrollLength/fadeUntil;
}
heroContent.css({
'opacity' : opacity,
});
if (scrollLength < scroll1){
$('.fixed-nav').removeClass('fixed');
}
if (scrollLength > scroll1 && scrollLength < scroll2){
$('.fixed-nav').addClass('fixed');
chapterNum.text('01');
window.location.hash = "story1";
$('.fixed-nav ul li').removeClass('active');
$('.fixed-nav ul li:first-of-type').addClass('active');
}
if (scrollLength > scroll2 && scrollLength < scroll3) {
chapterNum.text('02');
window.location.hash = "story2";
$('.fixed-nav ul li').removeClass('active');
$('.fixed-nav ul li:nth-of-type(2)').addClass('active');
}
if (scrollLength > scroll3 && scrollLength < scroll4) {
chapterNum.text('03');
window.location.hash = "story3";
$('.fixed-nav ul li').removeClass('active');
$('.fixed-nav ul li:nth-of-type(3)').addClass('active');
}
if (scrollLength > scroll4 && scrollLength < scroll5) {
chapterNum.text('04');
window.location.hash = "story4";
$('.fixed-nav ul li').removeClass('active');
$('.fixed-nav ul li:nth-of-type(4)').addClass('active');
}
if (scrollLength > scroll5) {
chapterNum.text('05');
window.location.hash = "team";
$('.fixed-nav ul li').removeClass('active');
$('.fixed-nav ul li:nth-of-type(5)').addClass('active');
}
});
});
最佳答案
一些提示:
- 您将在每次调整大小时设置一个新的事件监听器。
- 每当您编写
$("..")
时,jQuery 都会在 DOM 树中搜索您想要定位的元素。这是一个“昂贵”的行动。尝试跟踪您需要在滚动时执行的方法外部更改的元素。 - 使用
else if
来阻止对所有if
语句进行求值。
例如:
if (scrollLength < scroll1){ /* .. */ }
if (scrollLength > scroll1 && scrollLength < scroll2) { /* .. */ }
也可以写成:
if (scrollLength < scroll1){ /* .. */ }
else if (scrollLength < scroll2) { /* .. */ }
关于javascript - 更新滚动和其他滚动事件上的哈希值 - 性能问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36698784/