私は次のスクロールイベントを持っています。スクロールでは、ユーザーがページ内のどのセクションに応じてナビゲーションスタイルを更新するかを測定します。問題は、スクロールで実行している計算がかなりチャンクで、速度が遅くなります。スクロールするときに少しページ。ここに私のコードは次のとおりです。スクロールイベントが遅いです - 軽い方法がありますか?
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空腹な方法があるかどうかを知るのが大好きです。あなただけのコールの量を遅らせるために探している場合、これは、これは私が実際にここにあるいくつかのコードです
var waitForFinalEvent = (function() {
var timers = {};
return function (callback, ms, uniqueId) {
if (!uniqueId) {
uniqueId = "Don't call this twice without a uniqueId";
}
if (timers[uniqueId]) {
clearTimeout (timers[uniqueId]);
}
timers[uniqueId] = setTimeout(callback, ms);
};
})();
仕事ができる私が持っていない私を許して
乾杯
http://ejohn.org/blog/learning-from-twitter/、https://でCSS -tricks.com/debouncing-throttling-explained-examples/ – CBroe