首页 > 解决方案 > 如何在Javascript中水平显示不同高度的矩形?

问题描述

我正在网站上制作新闻页面,并且我将标题/文章设置在矩形中,使用

.press-blocks{
    column-count: 4;
    column-gap: 2em;
    padding-left: 10%;
    padding-right: 10%;
}
.press-item{ 
    display: inline-block;
    margin: 0 0 5em;
    width: 100%;
    text-align: justify;
}

页面的整个“新闻”部分区域在一个大部分press-blocks中,每篇文章都有自己的press-item. 这样,当写一篇新文章时,我可以把它放在页面的开头,所有文章都会按时间顺序排列。但是,时间顺序是从上到下,从左到右,如下所示:

1    5    9    13
2    6    10   14
3    7    11   15
4    8    12   16

有没有办法把它从左到右,从上到下?

1    2    3    4
5    6    7    8
9    10   11   12
13   14   15   16

我查看了 W3Schools 教程display: inline-block,它们是水平的,但不同之处在于它们没有固定的列数。我希望它始终只有 4 列,并且在我添加新列时进一步向下扩展,就像现在一样。我还想保持项目之间的垂直距离。

想象一下,这些矩形都是均匀分布的,并且它们之间的水平和垂直距离相同。 矩形当前外观的粗略绘制版本。

标签: javascripthtmlcssformat

解决方案


有两种方法可以解决这个问题。根据您对问题的评论的声音,您将想要制作一个使用 javascript 的砌体网格(第一个解决方案),但我还将包括一个 flex-box 解决方案,虽然它不会完全符合您的要求因为,它不使用javascript。


Javascript

这种方式使用 javascript 生成砖石网格,因为 CSS 无法单独完成。

例子:

<div class="masonry">
    <div class="masonry-brick">...</div>
    <div class="masonry-brick">...</div>
    <div class="masonry-brick">...</div>
    <div class="masonry-brick">...</div>
    <div class="masonry-brick">...</div>
    <div class="masonry-brick">...</div>
    <div class="masonry-brick">...</div>
    <div class="masonry-brick">...</div>
</div>
.masonry { 
    display: flex;
    flex-flow: column wrap;
    max-height: 800px; /* Or whatever you want the height to me */
    margin-left: -8px; /* Adjustment for the gutter */
    width: 100%;
}

.masonry-brick {
    margin: 0 8px 8px 0; /* Some gutter */
}
/**
 * @param grid       Object  The Masonry Element 
 * @param gridCell   Object  The Masonry bricks
 * @param gridGutter Integer The Vertical Space between bricks 
 * @param gridCol    Integer Number of columns
 */

function masonry(grid, gridCell, gridGutter, gridCol) {
    let g = document.querySelector(grid),
    gc = document.querySelectorAll(gridCell),
    gcLength = gc.length, // Total number of cells in the masonry
    gHeight = 0, // Initial height of our masonry
    i; // Loop counter

    // Calculate the net height of all the cells in the masonry
    for(i=0; i<gcLength; ++i) {
        gHeight+=gc[i].offsetHeight+parseInt(gridGutter);
    }

    // Calculate and set the masonry height
    g.style.height = gHeight/gridCol + gHeight/(gcLength+1) + "px";
}

masonry(".masonry", ".masonry-brick", 8, 4);

弹性盒

这种方式在块的父 div 上使用display: flex;flex-wrap: wrap;,然后将每个块设置为具有25%父级的宽度。

例子:

<div class="parent">
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
</div>
.parent {
    display: flex;
    flex-wrap: wrap;
    width: 100%;
}
.child {
    height: 200px;
    width: 25%;
    background-color: red;
}

两种方式都可以实现您想要的从左到右、从上到下的外观。但只有 javascript 脚本方式才能将每个“单元格”单独定位为自定义高度。


推荐阅读