如何优化js代码

时间:2015-05-26 20:17:29

标签: javascript jquery html

如何优化我的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 个答案:

答案 0 :(得分:0)

您可以按类循环使用each来检查所有可见元素 获取id并将其拆分以获取数字并切换等效元素active类 我把它放到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');
        }
    });
}