首页 > 解决方案 > 适合任何宽度/高度容器的正方形网格

问题描述

我正在尝试创建一个可以适合任何尺寸容器的正方形网格(即,如果容器宽度/高度发生变化,正方形会自行调整大小或添加/删除新的)。

我现在正在使用 Javascript 路线(和 Jquery,现在) - 可能有一个 flexgrid 解决方案,但由于我计划用某种细胞自动机类型的东西填充我的方块,我认为它不会受到伤害。并不能解决我的问题,因为正方形的行数似乎是固定的。

这是我到目前为止所拥有的:

var screen = {
  width: 0, // these I get with jquery, on load and on resize events
  height: 0
}

var values = {
  min: 100, // minimum square size
  max: 500 // maximum square size
}

var findSize = function() {
  var r = 1; 
  var currVal = values.min;
  while (r > 0) {
    if((screen.width % currVal) === (screen.height % currVal)) {
      // this should mean that they are both divisible by this value, right?
      // get out of the loop and return value
      r = 0;
      return currVal;
    } else if (currVal > values.max ) {
      // if we exceed the maximum size, get out of the loop and return 0
      r = 0;
      return 0;
    } else {
      // if not, increment a bit
      currVal += 0.25; // increment the value to check the modulo against
    }
  }
}

调用该findSize()函数应该返回正方形的尺寸(然后我可以轻松地构建我的网格,使用浮动的正方形或绝对定位的正方形。

问题是它没有。好吧,有时确实如此。而且它也经常给我什么...

不工作的网格

边框已完成,box-shadow因此不应影响尺寸。

所以我想知道...

非常感谢!

标签: javascriptjquerycss

解决方案


这段代码的问题是它试图找到解决方案,但未能解释每个增量(0.25)之间的答案。

此外,如果可以有任意数量的单元格(自动添加删除),那么答案也可以是“总是 100”。

我想你在这里想要实现的是一个“最合适的”,它可以同时在水平和垂直方向上不留边界。我不确定该问题是否有正确的答案(您可能需要搜索Greatest common divisor,接近您正在做的事情),我想知道下面的代码是否不适用于您的情况:

var findSize = function() {
  var ratio = screen.width / screen.height; // get the ratio between width and height
  if (ratio > 1) {
    ratio = 1 / ratio; // always have it always <= 1
  }
  var size = values.max * ratio; // size between 0 and max
  if (size < values.min) {
    return values.min; // failed, could try other things here
  }
  return size; // size between min and max
}

推荐阅读