更新版本:
当您从用户那里获取输入时,每次使用 onchange 事件来获取输入标签的值。
HTML:
<input onchange="fillSquare()" id="quantity" type="number" min="0"/> //You can use any input type
Javascript:
function fillSquare(){
var Q = $("#quantity").val();
var i = Math.sqrt(Q); // Here I'm taking square root of 'Q' to calculate width and height of small sqaures.
$('.smaller-square').css({
"width": (100% / i),
"height": (100% / i)
});
}
旧解决方案:
我认为 CSS 中的 calc 属性更适合您的要求。
首先确保你有一些像下面这样的 css 来制作它们。
.square{
display:block;
width: 500px; //Any number is fine, until both height and width are same
height: 500px; //Make sure you've some numbers here, as we are going to deal with width and height of smaller-square in percentages
}
.smaller-square{
display:inline-block;
float:left;
}
现在您可以通过两种方式实现此目的,一种是纯 CSS(您要求的那种),另一种是使用一些 Javascript 库。
首先,CSS:
.smaller-square{
width:calc(100% / i);
height:calc(100% / i);
}
这里你必须硬编码 i 值,这意味着你在执行代码之前知道 i 值。
例如,如果 i=2 那么,
.smaller-square{
width:calc(100% / 2);
height:calc(100% / 2);
}
.smaller-square的宽度和高度是.square宽度和高度的50%。