简体   繁体   English

在JavaScript中以编程方式计算给定的面积和比例的宽度和高度

[英]Programmatically calculate width and height given area and ratio in JavaScript

OK, so I need to create an "auto fit" feature when a button is clicked. 确定,因此单击按钮时需要创建“自动调整”功能。

Pretend you have an area, which is variable in size due to the responsive nature of the page. 假设您有一个区域,由于页面的响应特性,该区域的大小是可变的。

This area can contain a number of rectangles (specified by how many logged in clients there are). 该区域可以包含多个矩形(由已登录客户端的数量指定)。

What I need to calculate, programmatically in JavaScript, is the appropriate width and height of each client in order to "fit" them all within that area. 我需要使用JavaScript以编程方式计算的是每个客户端的适当宽度和高度,以便将它们“适合”到该区域中。

var area = $('.client-container').width() * $('.client-container').height();
var noOfClients = 3; // normally calculated dynamically

// Ratio (1.25:1)
var r1 = 1.25;
var r2 = 1;

How can I work out what width and height I should apply to each client rectangle? 我如何确定应该对每个客户矩形应用的宽度和高度?

I assume you have full freedom to resize the N clients and that their natural aspect ratio can simply reflect that of the screen. 我假设您有充分的自由来调整N个客户端的大小,并且它们的自然纵横比可以简单地反映屏幕的纵横比。 You won't always be able to make all clients the same size without wasting space. 在不浪费空间的情况下,您将永远无法使所有客户端具有相同的大小。 Take the square root of N, round it down, and that's your number of rows R. It's also your number of columns except that X=NR*R clients don't fit. 取N的平方根,将其四舍五入,这就是您的行数R。它也是您的列数,除了X = NR * R客户不合适。 X is less than R. Just choose the bottom X rows and divide them into R+1 columns instead. X小于R。只需选择底部的X行并将它们分成R + 1列即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM