Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/79.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用绝对定位的li元素构建条形图_Javascript_Html_Css - Fatal编程技术网

Javascript 使用绝对定位的li元素构建条形图

Javascript 使用绝对定位的li元素构建条形图,javascript,html,css,Javascript,Html,Css,我正在尝试用元素构建一个“条形图”: 为了使s显示为垂直的“条”,从下到上,我将它们定位为绝对,并使用底部:0px。现在,我让它像这样手动工作: #graph { height: 300px; width: 400; border-bottom: 1px solid #CCC; position: relative; } #graph ul li { background: #0071bc; height: 200px; /* the he

我正在尝试用
  • 元素构建一个“条形图”:

    为了使
  • s显示为垂直的“条”,从下到上,我将它们定位为
    绝对
    ,并使用
    底部:0px
    。现在,我让它像这样手动工作:

    #graph {
        height: 300px;
        width: 400;
        border-bottom: 1px solid #CCC;
        position: relative;
    }
    #graph ul li {
        background: #0071bc;
        height: 200px;     /* the height will eventually be dynamic */
        width: 100px;
        display: block;
        position: absolute;
        bottom: 0px;
    }
    #graph ul li:nth-child(1) { left: 10px; }
    #graph ul li:nth-child(2) { left: 130px; }
    #graph ul li:nth-child(3) { left: 250px; }    /* and so on and so forth */
    
    这里有一个

  • 元素是这样被20px分开的-在这里可以进行计算。当我想向列表中添加额外的
  • 时,问题就出现了。事情是这样的:

    看到问题了吗

    现在,我可以添加更多的CSS来容纳额外的
  • ,但是每次都要这样做会变得乏味和低效


    有什么解决方案吗?

    如果您需要它来处理动态事务,您可以使用一个函数来迭代lis并设置
    左侧的位置

    如果有任何页面内交互(如页面加载后动态添加),您可以执行类似的操作,只需将
    $(li).each()
    更改为您需要的任何内容



    如果您知道它们永远不会超过某个特定的数字,那么添加CSS可能会更好。(遍历li:n个child(n){}以获得尽可能多的li)。

    你可以让sass为你做所有的数学运算:@supernova,是的,我试过了,
  • 不在
    图底部的边界上。
    @LarsEbert,不错!我没有想到,会给它一个目标,这些李将被动态添加(即,你不知道会有多少)?如果使用sass或更少的预处理器不起作用,那么使用jQuery/JS就非常简单了。(但没有比这更好的了:P)很乐意帮忙。检查我刚才的编辑,太。。。意外地在代码中留下了多余的一行。
    $('li').each(function(index){
            var xPos = index * 110 + 10;
            $(this).css('left', xPos);
    });