我认为我有一些可重用的代码,但是我不知道如何处理它

时间:2019-01-16 04:48:31

标签: jquery

由于相同的variable在代码中使用很多,我该如何处理

function contentsFade() {
    $(window).scroll(function () {
        $('.inner__section__contents').each(function () {
            var bottom_of_object = $(this).offset().top + $(this).outerHeight();
            var bottom_of_window = $(window).scrollTop() + $(window).height() + 100;
            if (bottom_of_window > bottom_of_object) {
                $(this).addClass('active');
            } else if (bottom_of_window < bottom_of_object) {
                $(this).removeClass('active');
            }
        });

        $('.photo__contents').each(function () {
            var bottom_of_object = $(this).offset().top + $(this).outerHeight();
            var bottom_of_window = $(window).scrollTop() + $(window).height() - 100;
            if (bottom_of_window > bottom_of_object) {
                $(this).addClass('active');

            } else if (bottom_of_window < bottom_of_object) {
                $(this).removeClass('active');
            }
        });
    }
}
  • 有多少variables可重复使用?
  • 什么是使此代码更简单,更省时的更好方法 根据情况可重复使用?

1 个答案:

答案 0 :(得分:1)

似乎唯一的区别在于+ 100- 100之间,因此您可以使用一个传递布尔变量的函数,该变量设置是加还是减:

const checkActive = (add) => function() {
  var bottom_of_object = $(this).offset().top + $(this).outerHeight();
  var bottom_of_window = $(window).scrollTop() + $(window).height() + (add ? 100 : -100);
  //                                                                  ^^^^^^^^^^^^^^^^^^
  if (bottom_of_window > bottom_of_object) {
    $(this).addClass('active');
  } else if (bottom_of_window < bottom_of_object) {
    $(this).removeClass('active');
  }
};

$('.inner__section__contents').each(checkActive(true)); // add 100
$('.photo__contents').each(checkActive(false)); // subtract 100

请注意,checkActive是一个返回一个函数的函数(返回的函数作为回调传递到.each

还要注意,根据您当前的逻辑,在checkActive情况下,bottom_of_window === bottom_of_object可能什么都不做。您可以考虑使用>=<=进行比较之一。