简体   繁体   中英

When using @keyframes to fade-out with opacity, how do I repeat the animation with the event?

I am making a label pop up for the user, if the user tries to drag and drop an element that has already been dragged.

Problem is, that the animations only happens once , and at the end of the animation, it will have an opacity of 0 forever.

CSS

@keyframes smooth {
0% { opacity: 1;}
100% { opacity: 0;}
}

.o_tip{
    position: absolute;
    z-index: 999;

    display: none;
    opacity: 0;

    -webkit-animation: smooth 2s ease-in;
    -moz-animation: smooth 2s ease-in;
    -o-animation: smooth 2s ease-in;
    -ms-animation: smooth 2s ease-in;
    animation: smooth 2s ease-in;
}

To illustrate my problem, if I 'end' the animation on opacity: 0.2 instead of opacity: 0 :

@keyframes smooth {
0% { opacity: 1;}
100% { opacity: 0.2;}
}

... then the label will reappear for each event - but it will not fade out again, which I want to do.

You can put the animation rule in a specific css class rule, and then on clicking add that class again. Just keep these points in mind:

  1. You need to remove the animation class first before adding it again to have any effect.
  2. Even if you follow first point, removing the class and adding it back right then won't have any visual effect. To trigger reflow, you can use this statement: void targetDiv.offsetWidth; .

 document.querySelector("#start-animation").onclick = function(e){ var targetDiv = document.querySelector("#mydiv"); targetDiv.className = ""; void targetDiv.offsetWidth; // this triggers UI reflow targetDiv.classList.add("o_tip"); }//onclick
 @keyframes smooth { 0% { opacity: 1;} 100% { opacity: 0;} } .o_tip{ z-index: 999; animation: smooth 2s ease-in forwards; } #mydiv{ background-color: yellow; height: 50px; width: 100px; } #mydiv.o_top{ display: block; }
 <div id="mydiv"></div> <button id="start-animation">Start animation</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM