admin 管理员组文章数量: 1086019
I have an example set up here on jsFiddle, the jQuery currently sets the width as a fixed pixel width. So when the browser width is decreased the bars go off the screen to the right. My question is how do i get jQuery to set the width to a percentage instead?
<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);
});
I have an example set up here on jsFiddle, the jQuery currently sets the width as a fixed pixel width. So when the browser width is decreased the bars go off the screen to the right. My question is how do i get jQuery to set the width to a percentage instead?
<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);
});
Share
Improve this question
edited Mar 10, 2013 at 0:42
Sunyatasattva
5,8603 gold badges28 silver badges40 bronze badges
asked Mar 4, 2013 at 23:29
Hugo DBHugo DB
901 silver badge6 bronze badges
3 Answers
Reset to default 4$(".meter > span").each(function() {
$(this).data("origWidth", ($(this).width() / $(this).parent().width()) * 100)
.width(0)
.animate({ width: $(this).data("origWidth") + "%" }, 3600);
});
FIDDLE
You have to first calculate the relative percentage between this two widths, like so:
var relativePercentage = ($(this).width()/$(this).parent('div').width())*100;
Then you can set this as the target width, remembering to add the %
number (or it will get the value in px
), like so:
$(this)
.data("origWidth", $(this).width())
.width(0)
.animate({
width: relativePercentage + '%'
}, 3600);
Working demo
This is all you need:
LIVE DEMO
$(".meter > span").each(function() {
$(this).animate({ width: $(this).data("width")+"%" }, 3600);
});
this HTML:
<span data-width="88"></span>
and in the CSS set width to 0%
;
Resizing the window your SPAN
s will keep the %
width.
本文标签: javascriptGet jQuery to set width as percentage rather than pixelsStack Overflow
版权声明:本文标题:javascript - Get jQuery to set width as percentage rather than pixels - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://roclinux.cn/p/1743985771a2513825.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论