CSS Visibility Animation Not working

2019-04-20 14:32发布

问题:

I want to do a keyframe based animation on the the visibility CSS property. I initially tried it on 'display' but found that animation on 'display' is not supported but 'visibility' is. The idea is to make visibility of rectangle keep toggling. I do not want to use jquery and want to implement whole of it in CSS. Following is my code but it does not give the expected result of the rectangle remaining hidden till the 5th second, appearing and then again disappearing at the end of animation

  <head>
      <style type="text/css">
     #layer1 {            
                -moz-animation-duration: 10s;                
        -moz-animation-name: toggle;
     }

     @-moz-keyframes toggle {
             from {
                visibility:hidden;
             }

         50% {
                    visibility:visible;
             }

         to {
         visibility:hidden;
          }
   }

  </style>

  <script type="application/javascript">
      window.onload = function()              
      {
           var c = document.getElementById('layer1');
           var ctxt = c.getContext('2d');
           ctxt.fillStyle = 'red';
           ctxt.fillRect(0,0,200,200);
           ctxt.fillStyle = 'green';
           ctxt.fillRect(0,0,100,100);
      }

  </script>

  <body>

        <canvas id="layer1" width="200" height="200" >         
   </canvas>

  </body>


</html>

回答1:

Visibility (and display) property can't be animated. An element is either visible or not. Try the opacity property instead:

@-moz-keyframes toggle {
    from {
        opacity:0;
    }

    50% {
        opacity:1;
    }

    to {
        opacity:0;
    }
}


回答2:

A CSS transition or animation on the visibility property keeps the element visible for the duration of the transition and then abruptly applies the new value. (assuming the current spec and as long as no special timing function is used.) Transitions/Animations on visibility do not show a gradually changing visual effect, however as I read the question the idea is indeed to keep the element hidden till the 5th second.

Your CSS animation specifies a first transition from 0% to 50% turning from hidden to visible which shows the element according to the rule above and then you specify a transition from 50% to 100% from visible to hidden, which also shows the element while playing. So the element it permanently visible.

By specifying

@keyframes toggle {
         from {
            visibility:hidden;
         }
     50% {
            visibility:hidden;
         }
     to {
            visibility:visible;
      }
 }

the element will stay hidden until 50% and then abruptly appear. To hide it at the end, you need to add visibility:hidden to the main style sheet rule not to the keyframes. Also see my blog post on CSS transition visibility http://www.taccgl.org/blog/css-transition-visibility.html#Appearance_CSS_Visibility