2015-05-26 215 views
0

如何優化我的JS代碼:如何優化js代碼

$(window).scroll(function() { 
    if ($('#sec1').isVisible()) { 
     $('.js-nav a.m1').addClass('active'); 
    } else { 
     $('.js-nav a.m1').removeClass('active'); 
    } 

    // ... 

    if ($('#sec5').isVisible()) { 
     $('.js-nav a.m5').addClass('active'); 
    } else { 
     $('.js-nav a.m5').removeClass('active'); 
    } 
}); 

http://jsfiddle.net/Kwiatkowski/qx8jodzx/

DIV有指一個菜單項

<div id="sec1" class="box-fh test1" data-menu="m1"> 
    <h1>box1</h1> 
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam diam orci, lobortis ut accumsan non, semper ut purus. Quisque ut blandit elit. Integer pulvinar dolor sit amet dictum auctor. Morbi sed felis et velit fringilla convallis. Nullam feugiat lectus id ultrices gravida. Fusce fringilla et dolor in egestas. Cras pretium euismod mauris, id luctus turpis dapibus at. Cras fringilla elit erat, vel dictum odio bibendum et.</p> 
    <div class="js-nav section-nav"> 
     <a class="next" href="#sec2">box2</a> 
    </div> <!-- .section-nav --> 
</div> 
+1

使用loooop !!! – Bergi

回答

0

可以使用each環中的屬性按類來檢查所有可見的元素。
獲取id並將其拆分得到號碼並切換等效元素active class。
我把它放到switchClass函數,並在滾動動畫完成後執行。

$('a[href*=#]:not([href=#])').click(function() { 
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && 
     location.hostname == this.hostname) { 
    var target = $(this.hash); 
    target = target.length ? target : $('[name=' + this.hash.slice(1) +']'); 

    if (target.length) { 
     $('html,body').animate({ 
     scrollTop: target.offset().top - 0 
     }, 1000, switchClass); 

     return false; 
    } 
    } 
}); 

$.fn.isVisible = function() { 
    var windowScrollTopView = $(window).scrollTop(); 
    var windowBottomView = windowScrollTopView + $(window).height(); 
    var elemTop = $(this).offset().top; 
    var elemBottom = elemTop + $(this).height(); 

    return ((elemBottom <= windowBottomView) && (elemTop >= windowScrollTopView)); 
} 


function switchClass() { 
    $('.box-fh').each(function() { 
    var nr = this.id.split('sec')[1]; 

     if($(this).isVisible()) { 
      $('.js-nav a.m' + nr).addClass('active'); 
     } else { 
      $('.js-nav a.m' + nr).removeClass('active'); 
     } 
    }); 
}