简体   繁体   中英

CSS / JS: Appended element does not animate

I'm trying to design a message box, that can be shown by calling the following function:

function showMsg(msg, state){ //state: -1: red, 0: orange (normal), 1: green
    var bg = document.createElement("div");
    bg.className = "msgBG";
    //RELEVANT ->

    var fg = document.createElement("div");
    fg.className = "msgFG";

    //<- RELEVANT
    var text = document.createElement("span");
    text.className = "msgText";
    text.innerText = msg;
    var button = document.createElement("button");
    button.className = "mediumButton msgButton";
    button.innerText = "OK";
    fg.appendChild(text);
    fg.appendChild(button);
    bg.appendChild(fg);
    document.body.appendChild(bg);
}

The idea is, that the fg fades in from the bottom of the page when created, so I used the following CSS to do that:

.msgFG{
    position:absolute;
    top: calc(50% - 200px);
    left: calc(50% - 300px);
    width:600px;
    height:400px;
    margin:0 auto;
    background-color:var(--bg-color);
    border: solid 5px var(--fg-color);
    border-radius:20px;
    animation-name: msgFGAppear;
    animation-delay: 5s;
}

@keyframes msgFGAppear{
    from{
        top:100%;
    }
    to{
        top: calc(50% - 200px);
    }
}

The fg is being created and positioned properly, but without the animation. So the final result is the one I want, but the animation doesn't fire in order to fade to that result ... What did I do wrong?

If you don't know what I mean, feel free to ask below.

I have created a plunkr for demo purpose.

You were missing an important property "animation-duration"

https://plnkr.co/edit/1sytQlOk90Du3ibGE6T5?p=preview

.msgFG{
  position:absolute;
  top: calc(50% - 200px);
  left: calc(50% - 300px);
  margin:0 auto;
  border-radius:20px;
  animation: msgFGAppear 12s normal ;
}

@keyframes msgFGAppear{
  from{
     top:100%;
  }
  to{
    top: calc(50% - 200px);
  }
}

change animation-delay: 5s; to animation-duration: 5s; and it will work

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