简体   繁体   中英

How to change the color of a bootstrap (twitter) progress bar at runtime

I am using this progress bar :

http://twitter.github.com/bootstrap/components.html#progress

And would like to give it a custom color, known only at runtime (so hardcoding it in the css or less file is not an option)

I have tried this :

<div class="progress">
  <div id='pb' class="bar" style="width: 80%"></div>
</div>

<script>
  $('#pb').css({'background-color': "red"})
</script>

without success.

Your code is actually working, just that the progress bar is actually using a gradient as a color instead of a solid background-color property. In order to change the background color, set the background-image to none and your color will be picked up:

$('#pb').css({
    'background-image': 'none',
    'background-color': 'red'
});

There is now a bootstrap 3.2 progress bar designer tool.

http://bootstrapdesigntools.com/tools/bootstrap-progress-bar-designer/

You should change the container div class in order to change the color.

Example using .progress-danger for red color:

<div class="progress progress-danger">
  <div class="bar" style="width: 60%;"></div>
</div>

More colors (just substitute button for progress in the class name). http://twitter.github.com/bootstrap/base-css.html#buttons

Update: In order to add the class name at runtime with javascript take a look at http://snipplr.com/view/2181/ or http://api.jquery.com/addClass/ if you are using jQuery.

Hope it helps.

Do you mean how to change the colours into one another at runtime?

I can only imagine you do as you have not marked anyone as being correct. In the case you do mean this, then have a look at this very minimal jsFiddle

HTML

<div class="progress">
    <div class="bar bar-success" style="width: 0%; opacity: 1;"></div>
</div>

JS

jQuery(document).ready( function(){
    window.percent = 0;
    window.progressInterval = window.setInterval( function(){
        if(window.percent < 100) {
            window.percent++;
            jQuery('.progress').addClass('progress-striped').addClass('active');
            jQuery('.progress .bar:first').removeClass().addClass('bar')
            .addClass ( (percent < 40) ? 'bar-danger' : ( (percent < 80) ? 'bar-warning' : 'bar-success' ) ) ;
            jQuery('.progress .bar:first').width(window.percent+'%');
            jQuery('.progress .bar:first').text(window.percent+'%');
        } else {
            window.clearInterval(window.progressInterval);
            jQuery('.progress').removeClass('progress-striped').removeClass('active');
            jQuery('.progress .bar:first').text('Done!');
        }
    }, 100 );
});

http://jsfiddle.net/LewisCowles1986/U9xw6/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM