【发布时间】:2016-04-18 15:51:53
【问题描述】:
我将多个事件绑定到一个滚动事件,当我尝试使用 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');
}
});
});
【问题讨论】:
标签: javascript jquery scroll