简体   繁体   中英

jQuery - Animate backgroundColor, depending on width percentage

I'm in the process of constructing rank/score bars for my device spec pages, and I have a basic animation using transition and animation together, but the end result isn't quite what I'm after. For your delectation, the CSS code is left in place (with the animation properties disabled), and this is currently how it stands - JSFiddle of the same thing .

A previous question of mine was to get the animation working, depending on the percentage of the bar, and the method I'm currently using is from the selected answer in that question. Unfortunately, the end result, while nice, doesn't provide the functionality I was originally after.

For example, as it currently is, the specific background color is provided when the page loads, and then the transition plays through.

What I was ideally after, is the result you get when the animation properties are enabled in my CSS, but again, that has problems of its own. It's closer to my target, but not the solution.

What I'm looking for is something like this (hopefully I have explained this well enough). All of these changes to the background color should happen while the transition (for the width) is happening.

  • When width equals 0% to 24%, the background color should be red, and so the bars will start off as red - #a41818

  • If width equals 25% to 49%, the background color should fade from red to orange - #87581c

  • If width equals 50% to 74%, the background color should fade from orange to yellow - #997815

  • If width equals 75% to 89%, the background color should fade from yellow to greenyellow - #659a1f

  • If width equals 25% to 49%, the background color should fade from greenyellow to green - #3a8d24

And also, if the width happens to stay at a specific percentage, such as 56%, for example, then the bar background color should stay at the color respective to its percentage range. In this case, 56% would be yellow. If the bar width is 12%, the color should stay red, etc.

Please do let me know if you need more detail, or if you need further clarification with anything.

Thanks!

If I understand correctly, you just want to animate colors based on what percent you're at when animating. Is this correct?

If so, and based on what you've provided with your example, I'd recommend looking into jQuery's animate function and using the step callback to check every step of the way in the animation.

Here is what I've experimented with so far with both css and jquery combined. I'd love to see a full css example!

The jQuery

// wrap this in an anonymous to help namespace collisions
// and to help with faster variable lookup.
;(function (document, $) {

    $(document).ready(function () {
        $('.rating-bar').each(function () {
            var _this = $(this),
                size = _this.data('size');

            _this.animate({
                width: size + '%'
            }, {
                duration: 2500,
                step: function (progress) {
                    _this.css({
                        backgroundColor: progressColor(progress)
                    });
                }
            });
        });
    });

    function progressColor(progress) {
        if (progress >= 0 && progress <= 24) return '#a41818';
        else if (progress >= 25 && progress <= 49) return '#87581c';
        else if (progress >= 50 && progress <= 74) return '#997815';
        else if (progress >= 75 && progress <= 89) return '#659a1f';
        else if (progress >= 90 && progress <= 100) return '#659a1f';
    }
})(document, jQuery);

The updated css

#rank-bar {
    margin: 1em 0 2em 0;
}
#rank-bar-score {
    display: inline-block;
}
#ranks-js {
    margin-bottom: 1.5em;
}
.rating-bar {
    width: 0;
    line-height: 2;
    background-color: #1a1a1a;
    outline: none;
    -moz-border-radius: 2px 0 0 2px;
    -webkit-border-radius: 2px 0 0 2px;
    border-radius: 2px 0 0 2px;
    -moz-transition: background-color 0.5s linear 0s;
    -webkit-transition: background-color 0.5s linear 0s;
    transition: background-color 0.5s linear 0s;
}
.rating-bar-bg {
    width: auto;
    background-color: #1a1a1a;
    margin: 0.5em 0 0 1em;
    border: 1px solid #090909;
    -moz-border-radius: 3px;
    -webkit-border-radius: 3px;
    border-radius: 3px;
}
.rating-bar-bg-overall {
    width: auto;
    background-color: #1a1a1a;
    margin: 0.5em 0;
    border: 1px solid #090909;
    -moz-border-radius: 3px;
    -webkit-border-radius: 3px;
    border-radius: 3px;
}
.rb-label {
    width: 10em;
    max-width: 350px;
    display: block;
    color: #ebebeb;
    font-weight: bold;
    text-shadow: 2px 1px 0 #222222;
    text-transform: uppercase;
    margin-left: 0.5em;
}
#overall {
    font-size: 1.25em;
}

JSFiddle

EDIT : I've added the updated css from the fiddle.

EDIT 2 : For a simple example, see this JSFiddle .

Another way to solve it.

The animation done with CSS, and scripting just to handle when to stop.

script

var intervalFunc;
var containerWidth;
var stopAt;

$(document).ready(function() {


$("#run").click(function() {
    containerWidth = $("#container").width();
    entered = $("#value").val();
    stopAt = containerWidth * entered / 100; 
    $("#test").removeClass ("animated");
    intervalFunc = setInterval (Stop, 10);
    setTimeout (Start, 10);
});

})

function Start () {
    $("#test").addClass ("animated");
    $("#test").removeAttr("style");

}

function Stop () {
    var elem = document.getElementById('test');
    var style = window.getComputedStyle (elem, null);
    var frame = style.getPropertyValue("width");
    var width = parseInt(frame,10);
    if (width > stopAt) {
        elem.style.webkitAnimationPlayState = "paused";
        clearInterval (intervalFunc);
    }
}

CSS

#container {
    position: absolute;
    height: 50px;
    width: 300px;
    border: solid 1px black;
    display: block;
    top: 40px;
}

#test {
    position: absolute;
    height: 100%;
    width: 0px;
    display: block;
    top: 0px;
    left: 0px;
}

.animated {
    -webkit-animation-name: colors;
    -webkit-animation-duration: 4s;
    -webkit-animation-iteration-count: infinite;
    -webkit-animation-timing-function: linear;
}

#run {
    width: 40px;
    height: 25px;
}

@-webkit-keyframes colors
{
    0% {width: 0%; background-color: red;}
   30% {           background-color: red;}
   50% {           background-color: yellow;}
  100% {width: 100%; background-color: green;}
}

demo

In the demo, enter the percentage of the bar, and press run.

Only webkit animations, but should be easily extended to other browsers.

The color stops are only aproximate, but again can be easily modified.

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