由于相同的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
可重复使用?答案 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
可能什么都不做。您可以考虑使用>=
或<=
进行比较之一。