CSS3 animation: blinking overlay box

2019-03-20 06:58发布

问题:

I'd like to create a element which overlays a part of a page using position: absolute. This element would be 50% opaque and blink between red and transparent. A bit like what OSX uses (used?) to do for the default button of a dialog.

How to create a infinite animation loop with CSS3?

How to cycle between two background colours in this loop?

Which browsers is possible support today through CSS3 animation?

jQuery animation is an alternative, but I'd like to try CSS3 approach first.

回答1:

The first 2 questions are answered by the spec.

To loop: animation-iteration-count: infinite;

And cycling the background color involves specifying a @keyframes rule.


body { background: #0ff; }

@-webkit-keyframes blink {
    0% { background: rgba(255,0,0,0.5); }
    50% { background: rgba(255,0,0,0); }
    100% { background: rgba(255,0,0,0.5); }
}

@keyframes blink {
    0% { background: rgba(255,0,0,0.5); }
    50% { background: rgba(255,0,0,0); }
    100% { background: rgba(255,0,0,0.5); }
}

#animate { 
    height: 100px; 
    width: 100px;
    background: rgba(255,0,0,1);
}

#animate {
    -webkit-animation-direction: normal;
    -webkit-animation-duration: 5s;
    -webkit-animation-iteration-count: infinite;
    -webkit-animation-name: blink;
    -webkit-animation-timing-function: ease;   

    animation-direction: normal;
    animation-duration: 5s;
    animation-iteration-count: infinite;
    animation-name: blink;
    animation-timing-function: ease;       
}

(don't forget any applicable vendor prefixes!)

As far as browser support goes, i couldn't tell you specifics, but in any case i would recommend feature detect via modernizr and a javascript fallback.

Here is an example that works in webkit and fulfills at least some of your requirements. NOTE: I don't use a mac so i wasn't sure the specifics of the effect you referenced.



回答2:

Once you've set the animation up in the stylesheet (-webkit-transition:), you can simply change the color with JavaScript.

function toggleColor(element)
{
    var red = "rgba(255,0,0,0.5)";
    var transparent = "rgba(255,0,0,0)";
    element.style.backgroundColor = ((element.style.backgroundColor == red) ? transparent : red);
    window.setTimeout(function()
    {
        toggleColor(element);
    });
}

Currently, only Webkit browsers (Safari & Chrome) support CSS-Animations.