不太熟悉float属性,入了flex的坑,感觉这flex是真心好用,但也有个小问题,space-between虽然能自动生成等间距,如果是多行排列的情况,底行元素数量不足的时候,space-between同样会自动计算间距,这个时候问题来了,上面一排有4个,最后一排就俩,这间距当然就不一样了么。
百度了一下解决的方案,感觉用js动态添加一些填充元素更加灵活方便。博主的容器css写成了自适应,根据页面宽度依次2,3,4,5个元素同行排列。所以js也需要根据对应的宽度来动态填充。附上js源码备忘:
//fillItem
function getViewportWidth() {
return window.innerWidth || document.documentElement.clientWidth;
}
function adjustCategoryItems() {
let $container = $('.category-post');
let items = $container.find('article.category-post-item');
let placeholder = $container.find('article.category-post-placeholder');
if (items.length === 0) {
return; // 如果没有item,直接退出函数
}
let itemCount = items.length - placeholder.length;
let windowWidth = getViewportWidth();
let modulo;
// 根据窗口宽度确定模数
if (windowWidth >= 992) {
modulo = 5;
} else if (windowWidth >= 768) {
modulo = 4;
} else if (windowWidth >= 568) {
modulo = 3;
} else {
modulo = 1; // 小于568px时不补充
}
// 计算需要补充的数量
let remainder = itemCount % modulo;
let itemsToAdd = (remainder === 0) ? 0 : (modulo - remainder);
// 移除之前可能添加的占位元素
$container.find('article.category-post-placeholder').remove();
// 如果需要补充元素且数量大于0
if (itemsToAdd > 0) {
for (let i = 0; i < itemsToAdd; i++) {
$container.append(
$('<article/>', {
'class': 'category-post-item category-post-placeholder',
'aria-hidden': 'true',
'style': 'visibility: hidden;'
})
);
}
}
}
// 页面加载时执行一次
adjustCategoryItems();