滚动事件运行缓慢-有更简便的方法吗? [英] scroll event running slow - is there a lighter way?

查看:125
本文介绍了滚动事件运行缓慢-有更简便的方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下滚动事件,该事件在滚动时会测量用户在页面中的位置,并根据他们所在的部分来更新导航样式.问题是我在滚动时执行的计算非常笨拙,并且速度变慢滚动时向下翻页一点.这是我的代码:

I have the following scroll event that on scroll measures where in the page the user is and updates the navigation styling according to which section they are in. The problem is the calculation i'm performing on scroll is quite chunky and it slows down the page a little bit when scrolling. Here is my code:

screenHeight = $(window).height();
screenHeightRatio = screenHeight*0.3;
//here I calculate screen height plus the ratio of the screen height I would like for the menu elements to change

aboutOffset = $(".aboutcontainer").offset().top - screenHeightRatio;
portfolioOffset = $(".portfoliocontainer").offset().top - screenHeightRatio;
musicOffset = $(".musiccontainer").offset().top - screenHeightRatio;
contactOffset = $(".contactcontainer").offset().top - screenHeightRatio;
// here I calculate the offset for each section in the screen



$(window).scroll(function(){
var amountScrolled = $(document).scrollTop();
//here I see how far down the page the person has scrolled

if($(".header-options").hasClass("portfolio-inner-active")) { 
return;
// here I cancel the scroll event if they are in a certain section

} else {

if(contactOffset <= amountScrolled) {
// each of the following if statements will calculate if the amount scrolled surpasses the various section offsets I defined outside of the scroll function

    $(".header-options li").removeClass("active");
    $(".contactbutton").addClass("active");
 history.pushState('page2', 'Title', '/contact');
    return;
    } else {
        if(musicOffset <= amountScrolled) {
        $(".header-options li").removeClass("active");
        $(".musicbutton").addClass("active");
    history.pushState('page2', 'Title', '/music');
        return;
        } else {
            if(portfolioOffset <= amountScrolled) {
            $(".header-options li").removeClass("active");
            $(".portfoliobutton").addClass("active");
 history.pushState('page2', 'Title', '/portfolio');
            return;
            } else {
                if(aboutOffset <= amountScrolled) {
                $(".header-options li").removeClass("active");
                $(".aboutbutton").addClass("active");
             history.pushState('page2', 'Title', '/about');
            }
        }
    }
}
}

});

很想知道是否有一种减少CPU负担的方法,因为我真的希望在网站上产生这种效果.

Would love to know if there is a less cpu hungry way of doing this as I really want this effect on the site.

欢呼

推荐答案

使用 http://benalman.com/代码/项目/jquery-throttle-debounce/jquery.ba-throttle-debounce.js

这篇关于滚动事件运行缓慢-有更简便的方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆