Jquery 我想我有一些可重用的代码,但我不知道如何处理它
由于在代码中经常使用相同的Jquery 我想我有一些可重用的代码,但我不知道如何处理它,jquery,Jquery,由于在代码中经常使用相同的变量,因此如何处理此问题 function contentsFade() { $(window).scroll(function () { $('.inner__section__contents').each(function () { var bottom_of_object = $(this).offset().top + $(this).outerHeight(); var bottom_o
变量
,因此如何处理此问题
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');
}
});
}
}
函数contentsFade(){
$(窗口)。滚动(函数(){
$('.inner\u section\u contents')。每个(函数(){
变量bottom\u of_object=$(this.offset().top+$(this.outerHeight();
var bottom\u of_window=$(window.scrollTop()+$(window.height()+100;
if(窗口的底部>对象的底部){
$(this.addClass('active');
}else if(_窗口的底部_<_对象的底部_){
$(this.removeClass('active');
}
});
$('.photo\u contents')。每个(函数(){
变量bottom\u of_object=$(this.offset().top+$(this.outerHeight();
var bottom\u of_window=$(window.scrollTop()+$(window.height()-100;
if(窗口的底部>对象的底部){
$(this.addClass('active');
}else if(_窗口的底部_<_对象的底部_){
$(this.removeClass('active');
}
});
}
}
- 有多少
变量可以重用
- 有什么更好的方法可以使这段代码更加简单和多次 视情况而定
+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
constcheckactive=(add)=>function(){
变量bottom\u of_object=$(this.offset().top+$(this.outerHeight();
var bottom\u of_window=$(window.scrollTop()+$(window.height()+(add?100:-100);
// ^^^^^^^^^^^^^^^^^^
if(窗口的底部>对象的底部){
$(this.addClass('active');
}else if(_窗口的底部_<_对象的底部_){
$(this.removeClass('active');
}
};
$('.inner_uuuusection_uuucontents')。每个(checkActive(true));//添加100
$('.photo_ucontents')。每个(选中活动(false));//减去100
请注意,checkActive
是一个返回函数的函数(返回的函数作为回调传递给。每个
)
还注意到,给定当前逻辑,