我有一个设置here on 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);
});发布于 2013-03-05 07:38:45
您必须首先计算这两个宽度之间的相对百分比,如下所示:
var relativePercentage = ($(this).width()/$(this).parent('div').width())*100;然后,您可以将其设置为目标宽度,记住添加%数(否则它将获得px中的值),如下所示:
$(this)
.data("origWidth", $(this).width())
.width(0)
.animate({
width: relativePercentage + '%'
}, 3600);发布于 2013-03-05 07:35:36
$(".meter > span").each(function() {
$(this).data("origWidth", ($(this).width() / $(this).parent().width()) * 100)
.width(0)
.animate({ width: $(this).data("origWidth") + "%" }, 3600);
});https://stackoverflow.com/questions/15213132
复制相似问题