我已经为flexbox网格功能编写了一个脚本,但是我在计算最后一行上有多少项时遇到了一些问题,因为我希望对它们应用一个类,以便在不是整行的情况下修复flexbox样式。
我有4种布局:1列、2列、3列和4列。
在不同情况下,我会出现以下情况:
-
对于4列布局,底部行上可能还有3列。
-
对于4列布局,底部行上可能剩余2列。
-
对于4列布局,底部行上可能剩余1列。
-
-
对于3列布局,底部行上可能剩余1列。
-
在上述每种情况下,我都需要将不同的类添加到底部行的剩余项中,这些类包括:
-
-
弹性倒数第二项(用于一行中倒数第二项)
-
我当前的代码运行得很好,但是我遇到了一个实例,其中我的网格中有43个项目,并且数学似乎有问题。
随着屏幕尺寸越来越小,它会将布局调整得越来越小,直到其1列为止,这意味着计算必须在所有情况下都有效。
下面是我的代码:
jQuery(document).ready(function($) {
$(".flex-container").each(function() {
var flexColumns = $(this).attr("rel");
var self = $(this);
function flexboxFixes(){
if(self.find(".flex-item").hasClass("flex-cols-3")) {
var flexItemCount = self.find('.flex-cols-3').length;
if ((flexItemCount - 1) % 3 === 0) {
self.find(".flex-cols-3:last-of-type").addClass("flex-last");
} else if ((flexItemCount - 1) % 3 !== 0 && flexItemCount % 3 !== 0 ) {
self.find(".flex-cols-3:last-of-type").addClass("flex-last");
self.find(".flex-cols-3:nth-last-of-type(2)").addClass("flex-second-last");
}
} else if(self.find(".flex-item").hasClass("flex-cols-4")) {
var flexItemCount = self.find('.flex-cols-4').length;
if ((flexItemCount - 1) % 4 === 0) {
self.find(".flex-cols-4:last-of-type").addClass("flex-last");
} else if ((flexItemCount - 2) % 4 === 0) {
self.find(".flex-cols-4:last-of-type").addClass("flex-last");
self.find(".flex-cols-4:nth-last-of-type(2)").addClass("flex-second-last");
} else if ((flexItemCount - 2) % 4 !== 0 && flexItemCount % 4 !== 0) {
self.find(".flex-cols-4:last-of-type").addClass("flex-last");
self.find(".flex-cols-4:nth-last-of-type(2)").addClass("flex-second-last");
self.find(".flex-cols-4:nth-last-of-type(3)").addClass("flex-third-last");
}
} else if(self.find(".flex-item").hasClass("flex-cols-2")) {
var flexItemCount = self.find('.flex-cols-2').length;
if ((flexItemCount - 1) % 2 === 0) { //Is there 1 extra?
self.find(".flex-cols-2:last-of-type").addClass("flex-last");
}
}
}
flexboxFixes();
$(window).bind('resize',function(){flexboxFixes();});
});
});
值得注意的事项:
-
X/1总是等于整数
-
X/2始终等于整数或0.5
-
X/3总是等于整数或.33或.66
-
X/4总是等于整数或.25或.5或.75
-
-
2列,.5=1剩余
-
3列,.33=1剩余,.66=2剩余
-
4列,.25=1剩余,.5=2剩余,.75=3剩余
我在想一些事情,首先检查布局,然后检查十进制值,看看有多少项仍然存在,因为这将是所有数字相同?
var flexItemCount = self.find('.flex-cols-4').length;
var flexItemMath = flexItemCount / 4;
alert(flexItemMath % 1);
if (flexItemMath % columnCount) == 0.X