2013-11-28 36 views
0

我写了一个自定义脚本,它检查当前视口位置,然后相应地在固定页眉导航中突出显示当前项目。jQuery提高函数的性能

导航项目的顺序与偏移量变量声明的顺序相同。

我在scroll()上调用了这个函数,但是我感觉这并不是最好的表现,因为它会检查用户滚动的所有时间。也许更好的方法是例如检查滚动事件的结束?但我找不到实现这一点的方法。

你有什么想法我可以提高功能的性能?

这里是我的代码:

$window = $(window); 

$window.scroll(function() { 
      activeState(); 
     } 
    ); 

function activeState() { 
     var offsetHome = $('#Home').position().top; 
     var offsetLeistungen = $('#Leistungen').position().top; 
     var offsetPortfolio = $('#Portfolio').position().top; 
     var offsetUeber = $('#Ueber').position().top; 
     var offsetKontakt = $('#Kontakt').position().top; 
     var headerHeight = $('.header').height(); 
     $('#PrimNav li').removeClass('active'); 
     if($window.scrollTop() <= offsetLeistungen - headerHeight) { 
      $('#PrimNav li:nth-child(1)').addClass('active'); 
     } else if($window.scrollTop() <= offsetPortfolio - headerHeight) { 
      $('#PrimNav li:nth-child(2)').addClass('active'); 
     } else if($window.scrollTop() <= offsetUeber - headerHeight) { 
      $('#PrimNav li:nth-child(3)').addClass('active'); 
     } else if($window.scrollTop() <= offsetKontakt - headerHeight) { 
      $('#PrimNav li:nth-child(4)').addClass('active'); 
     } else { 
      $('#PrimNav li:nth-child(5)').addClass('active'); 
     } 
    }; 

谢谢!

回答

1

如果元素的位置是固定的,那么您可以将声明从activateState()函数中移出,因为每次滚动事件触发时都会再次声明这些变量,这并不是真正有效的。 您也不必在每个if语句中获得$(window).scrollTop()值。在滚动事件上计算一次,并将其值传递给activateState();

更新时间:

var offsetHome = 0; 
var offsetLeistungen = 0; 
var offsetPortfolio = 0; 
var offsetUeber = 0; 
var offsetKontakt = 0; 
var headerHeight = 0; 
$window = $(window); 

$window.scroll(function() { 
      activeState($window.scrollTop()); 
     } 
    ); 

function activeState(scrollTop) { 
     offsetHome = $('#Home').position().top; 
     offsetLeistungen = $('#Leistungen').position().top; 
     offsetPortfolio = $('#Portfolio').position().top; 
     offsetUeber = $('#Ueber').position().top; 
     offsetKontakt = $('#Kontakt').position().top; 
     headerHeight = $('.header').height(); 
     $('#PrimNav li').removeClass('active'); 
     if(scrollTop <= offsetLeistungen - headerHeight) { 
      $('#PrimNav li:nth-child(1)').addClass('active'); 
     } else if(scrollTop <= offsetPortfolio - headerHeight) { 
      $('#PrimNav li:nth-child(2)').addClass('active'); 
     } else if(scrollTop <= offsetUeber - headerHeight) { 
      $('#PrimNav li:nth-child(3)').addClass('active'); 
     } else if(scrollTop <= offsetKontakt - headerHeight) { 
      $('#PrimNav li:nth-child(4)').addClass('active'); 
     } else { 
      $('#PrimNav li:nth-child(5)').addClass('active'); 
     } 
    }; 
+0

谢谢您的回答。不幸的是你误解了我,元素的位置并不固定,只是标题导航的位置,我突出显示当前的可视元素是固定的。 #Home,#Leistungen,..的位置在页面上的某处,并且可以在用户浏览页面时更改。但是我在''activeState()'函数调用中使用了'$ window.scrollTop()'。 – Sebsemillia

+1

在这种情况下,您仍然可以拆分声明和分配。请参阅上面的更新代码。 – zfor

+0

是的,这是有道理的!我会等到明天再看看别人是否会给我意见,我会决定接受哪个答案。但是现在你处于领先地位......;)谢谢! – Sebsemillia