javascript - 适合任何宽度/高度容器的正方形网格
问题描述
我正在尝试创建一个可以适合任何尺寸容器的正方形网格(即,如果容器宽度/高度发生变化,正方形会自行调整大小或添加/删除新的)。
我现在正在使用 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
因此不应影响尺寸。
所以我想知道...
- 我的代码哪里出错了?
- 我可以改变我的函数,让它总是返回一些东西(也许增量更小?)。我可以使用四舍五入的值进行显示。
- 蛮力方面似乎不太有效。有没有办法重构这个,所以循环更短?
非常感谢!
解决方案
这段代码的问题是它试图找到解决方案,但未能解释每个增量(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
}
推荐阅读
- java - Using Contains for objects in List collection
- static - please explain every element of Java main ("public static void main(String[] args)")
- css - 如何在 Angular 6 中动态编译组件样式
- sql-server - Update multiple columns using union all
- java - 设置 onClickListener 时出现 NullPointerException
- react-native - code push react native not changed library updates on users App
- android - 在 api 19 中获取 recyclerView 的子项视图
- python - Pyplot yaxis 组织和标准化,在一个图中使用多个数据集
- microservices - How do you name teams working on a large application composed of many microservices?
- php - 未找到文件错误消息未出现在 Code Igniter 中