【发布时间】:2021-10-28 04:56:35
【问题描述】:
我正在一个网站上工作,我在 3x4 网格中列出了 12 个帖子。我正在使用绝对定位和一个 JS 代码来计算每个框的顶部和左侧位置(我正在使用这种方法,因为每个帖子都有不同的高度并且它必须按从左到右的顺序。如果有的话更好的解决方案我愿意接受。)
我正在使用 .outerHeight() 来获取每个帖子的高度并计算顶部位置。最后我选择了最大的列高并将其设置为容器高度。
我的问题是:当我打开页面时,JS 代码会生成我想要的布局,并且通常可以正常工作。但是有一些尝试,当它得到错误的值并且每列垂直滑动时,它也会计算容器的错误高度。
我怎样才能每次都完成这项工作?感谢您的帮助!
我的代码:
function latestPostLayout() {
var count = 0;
$(".latest-post:first-child").css({
top: "0",
left: "0",
});
var width = $(".latest-post:first-child").outerWidth();
$(".latest-post:nth-child(2)").css({
top: 0,
left: width,
});
var width2 = width + $(".latest-post:nth-child(2)").outerWidth();
$(".latest-post:nth-child(3)").css({
top: 0,
left: width2,
});
var count = 0;
var height0 = $(".latest-post:nth-child(1)").outerHeight();
var height1 = $(".latest-post:nth-child(2)").outerHeight();
var height2 = $(".latest-post:nth-child(3)").outerHeight();
$(".latest-post:gt(2)").each(function () {
if (count == 0) {
$(this).css({
top: height0,
left: 0,
});
height0 += $(this).outerHeight();
} else if (count == 1) {
$(this).css({
top: height1,
left: width,
});
height1 += $(this).outerHeight();
} else if (count == 2) {
$(this).css({
top: height2,
left: width2,
});
height2 += $(this).outerHeight();
}
count += 1;
if (count > 2) {
count = 0;
}
});
$(".dnh-latest-posts").css({
height: Math.max(height0, height1, height2),
});
}
【问题讨论】:
-
你能举个例子吗?
-
请修剪您的代码,以便更容易找到您的问题。请按照以下指南创建minimal reproducible example。
标签: javascript html jquery css wordpress