Remove/Hide div from DOM after animation completes using CSS?

前端 未结 3 1577
南笙
南笙 2021-02-09 04:37

I have an animation where a div slides out the view, however when the animation is completed, the div just returns to its origin position in the view. How do I totally remove th

3条回答
  •  遥遥无期
    2021-02-09 05:22

    Use the animation-fill-mode option. Set it to forwards and the animation ends at it's final state and stay like that.

    Altered based upon comments Set opacity fade to just last 1% of animation... simplified keyframes. Added a jquery option to literally remove the div from the DOM. CSS alone won't alter the markup, where jQuery will.

    Although you can't animate the display property. If you want the div totally gone, after the opacity fades to zero, you can then add the display property to remove the div. If you don't wait for opacity to end, the div will just vanish without any transition.

    /* 
    
    This jquery is added to really remove 
    the div. But it'll essentially be 
    VISUALLY gone at the end of the 
    animation. You can not use, or 
    delete the jquery, and you really 
    won't see any difference unless 
    you inspect the DOM after the animation.
    
    This function is bound to animation 
    and will fire when animation ends. 
    No need to "guess" at timeout settings. 
    This REMOVES the div opposed to merely 
    setting it's style to display: none;  
    
    */
    
    $('.slide-box').bind('animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd', function(e) { $(this).remove(); });
    .slide-box {
      display: block;
      position: relative;
       left: 0%;
      opacity: 1;
      width: 100px;
      height: 100px;
      background: #a00;
      animation: slide 1s 1 linear forwards;
      
      /*
    	animation-name: slide;
    	animation-duration: 1s;
    	animation-iteration-count: 1;
    	animation-timing-function: linear;
    	animation-fill-mode: forwards;
     */
    }
    
    @keyframes slide {
      0% {
       left: 0%;
      opacity: 1;
      }
      99% {
        left: 99%;
        opacity: 1;
      }
      100% {
        left: 100%;
        opacity: 0;
        display: none;
      }
    }
    
    @-webkit-keyframes slide {
      0% {
        left: 0%;
      opacity: 1;
      }
      99% {
        left: 99%;
        opacity: 1;
      }
      100% {
        left: 100%;
        opacity: 0;
        display: none;
      }
    }
    
    

提交回复
热议问题