jQuery animate backgroundColor

前端 未结 17 2446
醉梦人生
醉梦人生 2020-11-21 07:11

I am trying to animate a change in backgroundColor using jQuery on mouseover.

I have checked some example and I seem to have it right, it works with other properties

17条回答
  •  清歌不尽
    2020-11-21 07:36

    I stumbled across this page with the same issue, but the following problems:

    1. I can't include an extra jQuery plugin file with my current set-up.
    2. I'm not comfortable pasting large blocks of code that I don't have time to read over and validate.
    3. I don't have access to the css.
    4. I hardly had any time for implementation (it was only a visual improvement to an admin page)

    With the above that pretty much ruled out every answer. Considering my fade of colour was very simple, I used the following quick hack instead:

    element
      .css('color','#FF0000')
    ;
    $('
    ') .css('width',0) .animate( {'width':100}, { duration: 3000, step:function(now){ var v = (255 - 255/100 * now).toString(16); v = (v.length < 2 ? '0' : '') + v.substr(0,2); element.css('color','#'+v+'0000'); } } ) ;

    The above creates a temporary div that is never placed in the document flow. I then use jQuery's built-in animation to animate a numeric property of that element - in this case width - which can represent a percentage (0 to 100). Then, using the step function, I transfer this numeric animation to the text colour with a simple hex cacluation.

    The same could have been achieved with setInterval, but by using this method you can benefit from jQuery's animation methods - like .stop() - and you can use easing and duration.

    Obivously it's only of use for simple colour fades, for more complicated colour conversions you'll need to use one of the above answers - or code your own colour fade math :)

提交回复
热议问题