简体   繁体   English

如何优化js代码

[英]How to Optimize js code

How can I optimize my JS code from: 如何从以下位置优化我的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/ http://jsfiddle.net/Kwiatkowski/qx8jodzx/

DIV has an attribute referring to a menu item 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>

You can use each loop by class to check all visible elements. 您可以按类使用each循环来检查所有可见元素。
Get id and split it to get number and switch equivalent element active class. 获取ID并将其拆分以获取数字并切换等效元素active类。
I put it to switchClass function and execute after animation of scrolling is done. 我将其放在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');
        }
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM