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

6

我已经在这里的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>

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

3个回答

4
$(".meter > span").each(function() {
   $(this).data("origWidth", ($(this).width() / $(this).parent().width()) * 100)
          .width(0)
          .animate({ width: $(this).data("origWidth") + "%" }, 3600);
});

FIDDLE


2

您需要先计算两个宽度之间的相对百分比,如下:

var relativePercentage = ($(this).width()/$(this).parent('div').width())*100;

然后您可以将此设置为目标宽度,记得添加“%”数字(否则它将获得“px”中的值),如下所示:
$(this)
    .data("origWidth", $(this).width())
    .width(0)
    .animate({
        width: relativePercentage + '%'
    }, 3600);

Working demo


1

这就是你所需要的:

LIVE DEMO

$(".meter > span").each(function() {
    $(this).animate({ width: $(this).data("width")+"%" }, 3600);
});

这是HTML代码:
<span data-width="88"></span>

在CSS中将宽度设置为0%;

调整窗口大小,您的SPAN将保持%宽度。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接