javascript - 让 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>
$(".meter > span").each(function() {
$(this)
.data("origWidth", $(this).width())
.width(0)
.animate({
width: $(this).data("origWidth")
}, 3600);
});
答案#1
$(".meter > span").each(function() {
$(this).data("origWidth", ($(this).width() / $(this).parent().width()) * 100)
.width(0)
.animate({ width: $(this).data("origWidth") + "%" }, 3600);
});
小提琴
答案#2
你必须首先计算这两个宽度之间的相对百分比,就像这样:
var relativePercentage = ($(this).width()/$(this).parent('div').width())*100;
然后你可以将其设置为目标宽度,记得添加 % 数字(否则它将以 px 获取值),如下所示:
$(this)
.data("origWidth", $(this).width())
.width(0)
.animate({
width: relativePercentage + '%'
}, 3600);
演示工作