获取jQuery将宽度设置为百分比而不是像素

Hug*_* DB 6 html javascript css jquery

在jsFiddle上设置了一个示例,jQuery当前将宽度设置为固定像素宽度.因此,当浏览器宽度减小时,条形图会从屏幕向右移动.我的问题是如何让jQuery将宽度设置为百分比?

<div class="bars">
    <div class="meter">
        <span style="width: 88%"></span>
    </div>
    <div class="meter">
        <span style="width: 62%"></span>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

$(".meter > span").each(function() {
    $(this)
        .data("origWidth", $(this).width())
        .width(0)
        .animate({
            width: $(this).data("origWidth")
        }, 3600);
});
Run Code Online (Sandbox Code Playgroud)

Sun*_*tva 2

您必须首先计算这两个宽度之间的相对百分比,如下所示:

var relativePercentage = ($(this).width()/$(this).parent('div').width())*100;
Run Code Online (Sandbox Code Playgroud)

然后你可以将其设置为目标宽度,记住添加%数字(否则它将获得 中的值px),如下所示:

$(this)
    .data("origWidth", $(this).width())
    .width(0)
    .animate({
        width: relativePercentage + '%'
    }, 3600);
Run Code Online (Sandbox Code Playgroud)

工作演示