Animate background color like a progress bar in jQuery

前端 未结 11 2174
南笙
南笙 2021-02-05 23:11

I have a div which has some text content( eg: My Name ) and the div is in RED background colour

11条回答
  •  感情败类
    2021-02-06 00:08

    Background gradient loader - possibly more appropriate

    You could also use the background gradient as the loader. Of course, jQuery doesn't natively support choosing correct CSS prefixes, so it may have to be tweeked to work in older browsers. But it'll work nicely where your browser supports linear-gradient.

    Since jQuery won't animate a background gradient, I've animated a span within it and am using the step option to change the gradient stops each time. This means that any duration or easing changes to the animate() will apply to the gradient as well:

    $("button").click(function(){    
        $('#loadContainer span').animate({width:'100%'}, {
            duration:10000,
            easing:'linear',
            step:function(a,b){
                $(this).parent().css({
                    background:'linear-gradient(to right, #0000ff 0%,#0000ff '+a+'%,#ff0000 '+a+'%,#ff0000 100%)'
                });
            }
        });
    });
    

    JSFiddle


    Original answer

    background-color is the CSS style, you are targeting the property of the javascript object, which in this case, is backgroundColor. You'll want to change the color name as well.

    $("button").click(function(){ 
        $('#myDivId').animate({backgroundColor:'blue'},10000);
    });
    

    JSFiddle

提交回复
热议问题