2
我想在用户到达特定部分时进行背景颜色动画更改。改善背景动画颜色变化
这里是jQuery代码我写道:
var initialColors = [];
$('section.changecolorbg').each(function(i){
initialColors[i] = $(this).css("backgroundColor");
});
$(window).scroll(function() {
$('section.changecolorbg').each(function(i){
if(isScrolledIntoView($(this))){
var bgc = initialColors[i];
$(this).parent().children('.changecolorbg').each(function(){
$(this).css("backgroundColor", bgc);
});
}
})
});
function isScrolledIntoView(elem)
{
var hT = elem.offset().top,
hH = elem.outerHeight(),
wH = $(window).height(),
wS = $(this).scrollTop() + 200;
return (wS > (hT+hH-wH))
}
的部分将会有一个背景颜色最初,这就是为什么我在一个变量保存它们。 这个问题在于它工作得很慢。我认为是因为所有的检查都需要在.scroll
函数中完成。
有没有一种方法可以改进代码?
P.S.我想达到的效果是一样的http://sfcd.com/
你在你的诊断是正确的 - 经济放缓的问题是,因为每个像素的'滚动()'处理火灾一旦UI更新的滚动。为了提高速度,您可以[debounce](http://stackoverflow.com/questions/9144560/jquery-scroll-detect-when-user-stops-滚动)事件。但是,这会导致一些滞后,这可能对您不适用。除了次要代码优化以外,没有其他选择。 –