最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get jQuery to set width as percentage rather than pixels - Stack Overflow

programmeradmin2浏览0评论

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
Add a ment  | 

3 Answers 3

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 SPANs will keep the % width.

发布评论

评论列表(0)

  1. 暂无评论