How do I animate a background color to transparent in jQuery?

后端 未结 12 1771
慢半拍i
慢半拍i 2020-12-09 14:46

I can animate from transparent to color, but when I tell jquery to animate the backgroundColor: \'transparent\' it just changes to white. Any idea how to fix this?

12条回答
  •  不思量自难忘°
    2020-12-09 15:21

    My solution was to animate to the colour seen by the user (ie. the colour of the parent element), and then set to the original colour (which may or may not be 'transparent') once the animation is finished

    var $t = $(some selector);
    
    var seenColour = findColour($t, 'background-color');
    var origColour = $t.css('background-color');
    $t.css('background-color', '#ffff99');
    $t.animate(
        {backgroundColor: seenColour}, 
        4000, 
        function(){ $t.css('background-color', origColour)}
    );
    
    function findColour($elem, colourAttr)
    {
        var colour = $elem.css(colourAttr);
        if (colour === 'transparent')
        {
            var $parent = $elem.parent();
            if ($parent)
            {
                return findColour($parent, colourAttr);
            }
            // Default to white
            return '#FFFFFF'; 
        }
        return colour;
    }
    

提交回复
热议问题