首页 > 解决方案 > 使用引导程序来布局可变项的网格模式的惯用方式

问题描述

我正在学习使用实用程序优先的 css 方法为可变数量的搜索结果创建网格模式布局。我想要实现的外观在这里用这张图片描述:

在此处输入图像描述

这是我使用引导 css 框架的解决方案。

function loadMore() {
   fetch('search-results.php?current='+document.querySelectorAll('.item').length)
   .then(response=>response.text())
   .then(result=>document.querySelector('.results').innerHTML += result);
}
body,div {padding:0;margin:0;}

.item {
  display:block;
  background:#333;
  color:white;
  border:2px solid white;
}

.item.col-12 {
  height:75vh;
}
.item.col-6 {
  height:50vh;
}
.item.col-4 {
  height:30vh;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>

<div class="results"></div>
<button type="button" onClick="loadMore()">Load More</button>

// PHP 文件 - search-results.php

<?php
//$n = rand(1,10);
$n = $_REQUEST['current'] < 1 ? 1 : 8;
for($c=0;$c<$n;$c++)
{
  $current = $c+intval($_REQUEST['current']);
  if(
    $current === 0 ||
    ($current-1)%8 === 0 ||
    ($current-3)%8 === 0 ||
    ($current+2)%8 === 0
  )
    echo '<div class="row">';

  if($current === 0)
    echo '<div class="item col-12">'.$current.'</div>';
  else if(($current-1)%8 === 0 || ($current-2)%8 === 0)
    echo '<div class="item col-6">'.$current.'</div>';
  else
    echo '<div class="item col-4">'.$current.'</div>';


  if(
    $current === 0 ||
    ($current-2)%8 === 0 ||
    ($current-2)%8 === 0 ||
    ($current-5)%8 === 0
  )
    echo '</div>';
}

我的引导方法有几个我不知道如何解决的问题:

  1. search-results.php返回随机数量的项目时,<div class="row">在多次单击“加载更多”按钮后,开始和结束标签不会在正确的时间插入。

  2. 我不喜欢为了正确放置 open 和 closee<div class="row">标签并决定是否编写col-12 || col-6 || col-4. 这一切似乎都不必要地复杂。

问题:使用引导程序(或任何其他实用程序优先的 css 方法)编写接收随机结果数的模式网格布局的惯用方式是什么?

额外 - 简单的方法

我上面的问题可以使用简单的 CSS 方法来解决,如下所示:

// CSS 文件

body,div {padding:0;margin:0;}
.results {
  display:flex;
  flex-wrap:wrap;
}
.item {
  display:block;
  background:#333;
  color:white;

  box-sizing:border-box;
  padding:10px;
  width:33.333%;
  height:30vh;
  border:2px solid white;
}
.item:nth-child(1) {
  width:100%;
  height:75vh;
}
.item:nth-child(8n+2),
.item:nth-child(8n+3) {
  width: 50%;
  height:50vh;
}

// PHP文件

<?php
$n = rand(1,10);
for($c=0;$c<$n;$c++)
  echo '<div class="item">'.($c+intval($_REQUEST['current'])).'</div>';

PHP 代码要简单得多,我不必处理包装<div>元素。

标签: phphtmlcsstwitter-bootstrapflexbox

解决方案


推荐阅读