根据元素的数量划分元素宽度

时间:2014-04-21 19:56:08

标签: javascript jquery html css

正如标题所说“根据元素的数量划分元素宽度” 我希望有一个类似进度的栏,我可以在其中添加元素,并根据进度条将分割的元素数量。

enter image description here

现在这是固定值(33%,33%和34%),我希望它们根据我使用的元素数量而改变。

就像我的列表中有4个元素一样,我想让它自动与4分开。有没有简单的方法可以做到这一点?也许只使用CSS?我不介意javascript,但我只是说它可能是我错过的东西:)

编辑: 我创建了3个div并给了他们所有不同的类。

<section class="progress-part-list">
    <div class="progress-part-left">

    </div>

    <div class="progress-part-right">

    </div>

    <div class="progress-part-mid">

    </div>
</section>

在我的CSS中,我的固定值是:

.progress-part-mid
{
    height: 100%;
    width: 34%;
    background-color: #52ff00;
    opacity: 0.9;
    display: block;
    float:left;
}

.progress-part-left
{
    height: 100%;
    width: 33%;
    background-color: red;
    opacity: 0.9;
    display: block;
    border-top-left-radius: 50px;
    border-bottom-left-radius: 50px;
    float:left
}

.progress-part-right
{
    height: 100%;
    width: 33%;
    background-color: yellow;
    opacity: 0.9;
    display: block;
    border-top-right-radius: 50px;
    border-bottom-right-radius: 50px;
    float:right;
}

3 个答案:

答案 0 :(得分:3)

你在找这样的东西吗?

http://jsfiddle.net/FK7N5/

您想要选择所有元素,并使用它来计算百分比。

您在容器中包含的元素数量并不重要。只要确保他们都有一个像#34; progress&#34;这样的公共课程。请记住,您可以在元素上拥有多个类,因此您可以拥有<div class="progress progress-first"><div class="progress progress-middle">

让它运行的jQuery:

// Get all parts of the progress bar.
var bars = $('.bar');

// With each one, calculate the percentage and apply the width.
bars.each(function()
{
    $(this).css('width', (100 / bars.length) + '%');
});

答案 1 :(得分:0)

作为一个比我更应该使用javascript的人,首先想到的是在加载时运行一些JavaScript,然后它可以通过周围元素的'child'属性(带有类{ {1}}),然后除以100,然后将样式设置为。

以下是一些可以执行此操作的代码:

progress-part-list

将它放在<script type="text/javascript"> var divd=100/(document.getElementsByClassName('progress-part-list')[0].children.length); [].forEach.call(document.getElementsByClassName('progress-part-list')[0].children,function(curChild){ curChild.style.width=divd+'%'; }); </script>

的结束标记之后

这很粗糙,但是,您可能想要修复它以使其更优雅(例如修改类样式而不是内联样式,遍历所有而不仅仅是第一个<section>等等

它还没有经过测试

答案 2 :(得分:0)

尝试给每个内部元素赋予-4px的margin-right并使用以下JS / jQuery:

$(document).ready(function(){
    $('div div').width($('div:first-child').width() / 3);
});

这是一个小提琴:http://jsfiddle.net/JthgV/

这就是你要找的东西吗?

P.S。原谅内联风格。为了节省时间,我这样做了。