计算元素尺寸以适合容器内部 [英] Calculate elements dimensions in order to fit inside container

查看:157
本文介绍了计算元素尺寸以适合容器内部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个固定宽度235px和高度200px的ul。根据查询结果,此ul由n个数量的li填充。如何计算li的尺寸,以便它们填充ul中的所有可用空间。

I have an ul with fixed width 235px and height 200px. This ul is populated by n numbers of li depending on a query results. How can I calculate the dimensions of the li in order for them to fill all the available space inside the ul.

我已经尝试计算容器的周长,并将其与

I have tried calculating the container's perimeter and comparing it with the total of each element's perimeter but that doesn't work.

推荐答案

确定,这里是我尝试的代码,将工作一个公平高的覆盖 ul (不确定如果它实际上是最大的),给定的约束, li

OK, here's my attempt at code that will work out a fairly high coverage of the ul (not sure if it's actually maximal), given the constraints that the lis need not be square, but must all be the same size for any given number of items.

第一部分给出一个函数 getSquare(n)这将记住正方形的生成,所以如果你需要在一个页面上多次使用它,它不会保持重新计算的东西。

The first part gives a function getSquare(n) which will memoize the generation of squares, so that if you need to use it multiple times on a page it won't keep recalculating things.

部分是执行计算的函数。传递它的数量,以及你的容器的宽度和高度,它将返回一个对象的宽度和高度属性的项目。它不会保证整数结果。

The second part is the function that does the calculation. Pass it the number of items, and the width and height of your container, and it will return an object with width and height properties for the items. It doesn't ensure integer results.

throw的行只是为了测试目的,可以删除。

The line with the throw is just there for testing purposes really, could be removed.

var getSquare = (function()
{
    var squares = [];
    return function(n)
    {
        if (!squares[n])
        {
            squares[n] = Math.pow(n, 2);
        }
        return squares[n];
    };
})();


function calcItemDimensions(itemCount, areaWidth, areaHeight)
{
    var x, y, slots,
        n = 0,
        sq = 0;

    while (itemCount > sq)
    {
        n += 1;
        sq = getSquare(n);
    }

    x = y = n;
    slots = sq;

    while (slots - itemCount >= x)
    {
        if (x === y) { y -= 1; }
        else { x = y; }
        slots = x * y;
        if (slots < itemCount) { throw new Error('slots < itemCount: ' + slots + ' < ' + itemCount); }
    }

    return { width: areaWidth / x, height: areaHeight / y };
}

这篇关于计算元素尺寸以适合容器内部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆