我有三个jQuery函数,其中包含一个if / else if语句。基本上,每个不同的函数都会根据窗口宽度是小于还是大于某个特定值来切换/删除不同的css类。
所有功能都非常相似,我一直在尝试将它们缩短/组合为一个功能。我敢肯定它可以很容易地缩短,但是我不知道怎么做!
这是jQuery:
jQuery(document).ready(function($) {
$('.exampleimg').click(function() {
$('.about').hide(600);
if (($(window).width() > 670) && ($(this).hasClass('exampleimgopen'))) {
$(this).removeClass('exampleimgopen');
}
else if ($(window).width() > 670) {
$('.exampleimg').removeClass('exampleimgopen');
$(this).addClass('exampleimgopen');
}
});
});
jQuery(document).ready(function($) {
$('.exampleimg').click(function() {
$('.about').hide(600);
if (($(window).width() < 670) && ($(this).hasClass('exampleimgopen2'))) {
$(this).removeClass('exampleimgopen2');
}
else if ($(window).width() < 670) {
$('.exampleimg').removeClass('exampleimgopen2');
$(this).addClass('exampleimgopen2');
}
});
});
jQuery(document).ready(function($) {
$('.exampleimg').click(function() {
$('.about').hide(600);
if (($(window).width() < 540) && ($(this).hasClass('exampleimgopen3'))) {
$(this).removeClass('exampleimgopen3');
}
else if ($(window).width() < 540) {
$('.exampleimg').removeClass('exampleimgopen3');
$(this).addClass('exampleimgopen3');
}
});
});
为了保留所有功能,我必须创建一个包含3个变量的函数:
function image(condition, windowWidth, css) {
return function() {
$('.about').hide(600);
var windowCondition = condition($(window).width(), windowWidth);
if (windowCondition && ($(this).hasClass(css))) {
$(this).removeClass(css);
}
else if (windowCondition) {
$('.exampleimg').removeClass(css);
$(this).addClass(css);
}
}
}
var lessThan = function(a, b) { return a < b; };
var greaterThan = function(a, b) { return a > b; };
var func1 = image(greaterThan, 669, 'exampleimgopen');
var func2 = image(lessThan, 670, 'exampleimgopen2');
var func3 = image(lessThan, 540, 'exampleimgopen3');
$('.exampleimg').click(func1);
$('.exampleimg' ).click(func2);
$('.exampleimg').click(func3);
并且还创建两个变量来管理小于和大于670px
只需单击即可调用每个类的函数
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句