我有以下滚动事件,滚动测量用户在页面中的位置,并根据它们所在的部分更新导航样式。问题是我在滚动上执行的计算非常粗糙滚动时,它会慢慢减慢页面的速度。这是我的代码:
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饥饿方式这样做,因为我真的希望这个效果在网站上。
干杯
答案 0 :(得分:2)
使用Ben Alman的jQuery throttle / debounce
$(window).scroll( $.throttle( 250, function(){...} ) );
http://benalman.com/code/projects/jquery-throttle-debounce/jquery.ba-throttle-debounce.js
答案 1 :(得分:1)
如果您希望延迟通话量,那么这可以正常工作
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);
};
})();
这是我在这里找到的一些代码,请原谅我没有链接回原始来源的网址。这将延迟滚动后调用X秒数。这意味着,它不会在那个时间框架内拨打五十亿次电话,而是制作一个只能提供帮助的电话。
你打电话的方式是这样的:
waitForFinalEvent(function() {
//stuff to do
}, 500, "randomString");
希望这有帮助!!将500调整为您想要延迟的时间。
原始邮寄:JavaScript/JQuery: $(window).resize how to fire AFTER the resize is completed?