【问题标题】:Javascript height calculating and positioningJavascript高度计算和定位
【发布时间】: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


【解决方案1】:

使用 CSS 网格。它是为解决此类复杂的网格需求而设计的。

CSS 应该是这样的:

    .container {
      display: grid;
      /* To make equal width columns */
      /* assuming you want 3 cols per row */
      grid-template-columns: 1fr 1fr 1fr;
      /* To make equal height rows */
      /* assuming you have 4 rows (because 12/3 = 4) */
      grid-template-rows: 1fr 1fr 1fr 1fr;
    }

一行中网格列的高度将使用/匹配该行中最大列的高度,有点像您使用 HTML 表格元素。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-29
    • 1970-01-01
    • 2017-10-21
    • 1970-01-01
    • 2011-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多